Hello everyone!
I have been doing quite a bit of DevOps work lately and I received a request the other day that might be worth sharing.
Our SCSM Administrator needed to get an export of our current categories, and he had found a script online to do so; however, it was only hard coded to go 3 levels deep and our categories would go much deeper than that. . He asked me if I could take a look into why this was happening, and it turned out that the way that the script works is that it was only hard coded to go 3 levels deep, so I wrote a function to recursively go through the main class, and its children and print out the categories regardless of the levels that you might have.
Import-Module SMLets
function get-childLists($listObjects)
{
$count ++
foreach($obj in $listObjects)
{
$id = $obj.id
"$("`t"*$count) - $($obj.DisplayName)" | Out-File 'C:\FILE\PATH.txt' -Append
$children = Get-SCSMEnumeration -ComputerName $scsm | ? Parent -match $id
if($children -ne $null)
{
get-childLists $children, $listName
}
}
}
$scsm = 'YOURSCSMSERVER'
$areas = @("ActivityAreaEnum",
"IncidentClassificationEnum",
"ServiceRequestAreaEnum")
foreach($list in $areas)
{
$count = -1
$enumLists = Get-SCSMEnumeration -ComputerName $scsm | ? Name -eq $list
get-childLists $enumLists
}
Let me know what you think, and if you all find this useful then I can probably make it into an actual advance function.
Kind regards,
Me
Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts
Sunday, December 20, 2015
Friday, October 23, 2015
PowerShell 5.0
Hello everyone!
I might be a little late with this but the other day I found out a nice little feature of the new PowerShell 5.0, and that is that not only does it come with nice color coding but it also supports Control+C, Control-X and Control-V ! A feature that was long overdue.
Finding this new feature out made me realize that I haven't even looked into the new features, and so I did. Here are some of the features that I'm really excited about:
Let me know what you guys think about version 5.0, and if you are exited about any particular feature, and why!
Kind regards,
Me.
Edit: It has been pointed out to me that it is not PowerShell that is now able to handle the copy, cut and paste features but the shell. Thanks to https://www.reddit.com/user/No1Asked4MyOpinion for pointing it out.
I might be a little late with this but the other day I found out a nice little feature of the new PowerShell 5.0, and that is that not only does it come with nice color coding but it also supports Control+C, Control-X and Control-V ! A feature that was long overdue.
Finding this new feature out made me realize that I haven't even looked into the new features, and so I did. Here are some of the features that I'm really excited about:
- Microsoft.PowerShell.Archive: Allows us to manage, extract and even create compressed files (zip files)
- PowerShell Gallery: A central repository for all PowerShell things. If it is deployed correctly and it actually is used by the community it will be a great resources, specially with the new 'PowerShellGet' Module that allows you to get stuff from the Gallery.
- The new -Depth parameter for the Get-ChildItems cmdlet sounds great, so far I had to use a function that I wrote to get this accomplished. It'll be nice to have it already built in.
- Transcript is now supported in the ISE and a new GPO can be enabled to setup global transcripts.
- Get-Clipboard and Set-Clipboard cmdlet sound like might come in handy too! They support images, audio files, file lists, and text.
Overall it seems that this new version has come with quite a few changes very interesting changes. It's all very exciting. For more details be sure to visit the technet article.
Let me know what you guys think about version 5.0, and if you are exited about any particular feature, and why!
Kind regards,
Me.
Edit: It has been pointed out to me that it is not PowerShell that is now able to handle the copy, cut and paste features but the shell. Thanks to https://www.reddit.com/user/No1Asked4MyOpinion for pointing it out.
Thursday, May 14, 2015
Get-DFSNFolderTarget
Hello!
I been wondering how I can find out where a DFS target is through PowerShell for quite some time now, and perhaps I didn't look hard enough because today I found the cmdlet in the subject.
Get-DfsnFolderTarget [-Path] <String> [[-TargetPath] <String> ] [-CimSession <CimSession[]> ] [-ThrottleLimit <Int32> ] [ <CommonParameters>]
It is a very handy command that will return the following output:
PS Microsoft.PowerShell.Core\FileSystem::\\DFS\SHARE\PATH> Get-DfsnFolderTarget \\DFS\SHARE\PATH | fl * Path : \\DFS\SHARE\PATH State : Offline ReferralPriorityClass : sitecost-normal NamespacePath : \\DFS\SHARE\PATH ReferralPriorityRank : 0 TargetPath : \\targetServer\Share PSComputerName : CimClass : Root/Microsoft/Windows/dfsn:MSFT_DfsNamespaceFolderTarget CimInstanceProperties : {NamespacePath, ReferralPriorityClass, ReferralPriorityRank, State...} CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties
However, I have found it to be less than helpful if I don't know exactly
where the DFS namespace ends and the targetPath begins, for example:
\\DFS\SHARE\PATH\Something\Folder
If I try to find the root using this path I receive the following error:
Get-DfsnFolderTarget : Cannot get DFS folder properites on "Microsoft.PowerShell.Core\FileSystem::\\DFS\SHARE\PATH\Something\Folder" At line:1 char:1 + Get-DfsnFolderTarget $((Get-Item .\).PSParentPath) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (MSFT_DfsNamespaceFolderTarget:ROOT\Microsoft\...aceFolderTarget) [Get-Dfs nFolderTarget], CimException + FullyQualifiedErrorId : Windows System Error 1722,Get-DfsnFolderTarget Get-DfsnFolderTarget : A general error occurred that is not covered by a more specific error code. At line:1 char:1 + Get-DfsnFolderTarget $((Get-Item .\).PSParentPath) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (MSFT_DfsNamespaceFolderTarget:ROOT\Microsoft\...aceFolderTarget) [Get-Dfs nFolderTarget], CimException + FullyQualifiedErrorId : MI RESULT 1722,Get-DfsnFolderTarget
I am not sure why though. It is simple enough to get the information form the
GUI so perhaps is my inexperience or lack of knowledge, but why can't it be
this easy on the cmd line as well?
I do hope that it is just my lack of knowledge and that maybe one of you
might show me the right way to get the DFSFolderTarget path.
Kind regards,
Me
Tuesday, April 28, 2015
Script Sharing - Advance functions to make managing file security easier
Hey everyone!
I recently started trying to get a little bit more 'official' and started learning how to write Advance Functions and I wanted to share 4 functions that I believe are quite useful, and hope that someone might find helpful.
Function #1:
function Enable-AclInheritanceOnFolder
{
<#
.SYNOPSIS
This function will turn on inheritance on the folder
.DESCRIPTION
This function will turn inheritance on the folder provided, currenth path if no path is provided.
.EXAMPLE
Enable-AclInheritanceOnFolder -path 'C:\TestPath'
.PARAMETER Path
The path of the folder where the ACL should be added.
#>
[CmdletBinding()]
[OutputType([int])]
Param
(
#Path
[Parameter(Mandatory=$false,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='What is the path where inheritance should be enabled?')]
[Alias('Location')]
[ValidateLength(3,250)]
[string]$path
)
begin
{
if($path.Length -eq 0)
{
Write-Verbose "No Path provided, assigning current location to path."
$currentPath = (Get-Item .\).FullName
}
else
{
$currentPath = $path
}
}
Process
{
try
{
Write-Verbose "Getting folder IO object for $currentPath"
$folderInfo = New-Object IO.DirectoryInfo($currentPath)
Write-Verbose "Getting the Folder Access Control List."
$folderACLs = $folderInfo.GetAccessControl()
Write-Verbose "Enabling Inheritance in ACL Object."
$folderACLs.SetAccessRuleProtection($false,$false)
Write-Verbose "Attempting to save the changes."
$folderInfo.SetAccessControl($folderACLs)
}
catch
{
Write-Verbose "There was an error adding the permissions."
Write-Error $Error[0]
}
}
}
Function #2
function Disable-AclInheritanceOnFolder
{
<#
.SYNOPSIS
This function will turn off inheritance on the folder
.DESCRIPTION
This function will turn off inheritance on the folder provided, currenth path if no path is provided.
It will also require that you specify if the current rules should be kept and converted or if they
should be removed.
.EXAMPLE
Disable-AclInheritanceOnFolder -path 'C:\TestPath' -ConvertRules $true|$false
.EXAMPLE
Disable-AclInheritanceOnFolder -ConvertRules $true|$false
.PARAMETER Path
The path of the folder where the ACL should be added.
.PARAMETER ConvertRules
Bool to know if the current rules should be converted and kept or removed from the folder.
If you remove the rules you might be loose access to the folder, be sure to take ownership of the
folder first.
#>
[CmdletBinding()]
[OutputType([int])]
Param
(
#Path
[Parameter(Mandatory=$false,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='What is the path where inheritance should be disabled?')]
[Alias('Location')]
[ValidateLength(3,250)]
[string]$path,
#PreserveInheritance
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='Should the current rules be removed or converted?')]
[Alias('PreserveInheritance')]
[bool]$RemoveCurrentRules
)
begin
{
if($path.Length -eq 0)
{
Write-Verbose "No Path provided, assigning current location to path."
$currentPath = (Get-Item .\).FullName
}
else
{
$currentPath = $path
}
}
Process
{
try
{
Write-Verbose "Getting folder IO object for $currentPath"
$folderInfo = New-Object IO.DirectoryInfo($currentPath)
Write-Verbose "Getting the Folder Access Control List."
$folderACLs = $folderInfo.GetAccessControl()
Write-Verbose "Enabling Inheritance in ACL Object."
$folderACLs.SetAccessRuleProtection($true,$true)
Write-Verbose "Attempting to save the changes."
$folderInfo.SetAccessControl($folderACLs)
}
catch
{
Write-Verbose "There was an error adding the permissions."
Write-Error $Error[0]
}
}
}
Function #3
function Add-AclToFolder
{
<#
.SYNOPSIS
This function will add an Group to a folder's ACL.
.DESCRIPTION
This function will add the given SecurityGroup or user name to the specified folder.
.EXAMPLE
Add-ACL -Path 'C:\TestPath' -securityGroup 'DL-SECURITYGROUP-NAME'
.PARAMETER Path
The path of the folder where the ACL should be added.
.PARAMETER securityGroup
The security group name
.PARAMETER AccessLevel
The access level that you wish to give to the group. Choose between ReadAndExecute, Modify, FullControl
#>
[CmdletBinding()]
[OutputType([int])]
Param
(
#Path
[Parameter(Mandatory=$false,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='What is the path where this group should be added?')]
[Alias('Location')]
[ValidateLength(3,250)]
[string]$path,
#securityGroup
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='What is the name of the group?')]
[Alias('group')]
[ValidateLength(3,50)]
[string]$securityGroup,
#AccessLevel
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='Access Level: ReadAndExecute, Modify, FullControl')]
[Alias('acl')]
[ValidateLength(3,15)]
[string]$accessLevel
)
begin
{
Write-Verbose "Starting Add-AclToFolder Function."
if($path.Length -eq 0)
{
Write-Verbose "No path was provided. We are getting the current path."
$currentPath = (Get-Item .\).FullName
}
else
{
$currentPath = $path
}
}
Process
{
#region Add-ACL
Write-Verbose "Process has started."
try
{
Write-Verbose "Getting folder IO object for $currentPath"
$folderInfo = New-Object IO.DirectoryInfo($currentPath)
Write-Verbose "Getting the Folder Access Control List."
$folderACLs = $folderInfo.GetAccessControl()
Write-Verbose "Creating new Security.AccessControl.FileSystemAccessRule."
Write-Verbose "Security Group: $securityGroup"
Write-Verbose "Access Level: $accessLevel"
$newACL = New-Object System.Security.AccessControl.FileSystemAccessRule("$($securityGroup)",$accessLevel,"ContainerInherit, ObjectInherit", "None", "Allow")
Write-Verbose "Adding the new Rule to the ACL object."
$folderACLs.AddAccessRule($newACL)
Write-Verbose "Attempting to save the changes."
$folderInfo.SetAccessControl($folderACLs)
}
catch
{
Write-Verbose "There was an error adding the permissions."
Write-Error $Error[0]
}
}
}
Function #4
function Remove-AclFromFolder
{
<#
.SYNOPSIS
This function will remove an Group or User from a folder's ACL.
.DESCRIPTION
This function will remove an Group or User from a folder's ACL. If no path is provided the script will use the current path.
.EXAMPLE
Remove-AclFromFolder -Path 'C:\TestPath' -securityGroup 'DL-SECURITYGROUP-NAME'
.EXAMPLE
Remove-AclFromFolder -securityGroup 'DL-SECURITYGROUP-NAME'
.PARAMETER Path
The path of the folder where the ACL should be removed.
#>
[CmdletBinding()]
[OutputType([int])]
Param
(
#Path
[Parameter(Mandatory=$false,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='What is the path where th group should be removed from?')]
[Alias('Location')]
[ValidateLength(3,250)]
[string]$path,
#securityGroup
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='What is the name of the group?')]
[Alias('group')]
[ValidateLength(3,50)]
[string]$securityGroup
)
begin
{
Write-Verbose "Starting Add-AclToFolder Function."
if($path.Length -eq 0)
{
Write-Verbose "No path was provided. We are getting the current path."
$currentPath = (Get-Item .\).FullName
}
else
{
$currentPath = $path
}
}
Process
{
#region Add-ACL
Write-Verbose "Process has started."
try
{
Write-Verbose "Getting folder IO object for $currentPath"
$folderInfo = New-Object IO.DirectoryInfo($currentPath)
Write-Verbose "Getting the Folder Access Control List."
$folderACLs = $folderInfo.GetAccessControl()
Write-Verbose "Finding the rule to remove."
$aclToRemove = $folderACLs.Access | ?{$_.IdentityReference -match $securityGroup}
Write-Verbose "Removing $($aclToRemove.identityreference) from the ACL Object"
$folderACLs.RemoveAccessRule($aclToRemove)
Write-Verbose "Attempting to save the changes."
$folderInfo.SetAccessControl($folderACLs)
}
catch
{
Write-Verbose "There was an error modifying the permissions."
Write-Error $Error[0]
}
}
}
I believe that I been able to properly document the functions so there shouldn't be any confusion, but do let me know if you find any issues, comments or complaints.
Kind regards,
Me.
I recently started trying to get a little bit more 'official' and started learning how to write Advance Functions and I wanted to share 4 functions that I believe are quite useful, and hope that someone might find helpful.
Function #1:
function Enable-AclInheritanceOnFolder
{
<#
.SYNOPSIS
This function will turn on inheritance on the folder
.DESCRIPTION
This function will turn inheritance on the folder provided, currenth path if no path is provided.
.EXAMPLE
Enable-AclInheritanceOnFolder -path 'C:\TestPath'
.PARAMETER Path
The path of the folder where the ACL should be added.
#>
[CmdletBinding()]
[OutputType([int])]
Param
(
#Path
[Parameter(Mandatory=$false,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='What is the path where inheritance should be enabled?')]
[Alias('Location')]
[ValidateLength(3,250)]
[string]$path
)
begin
{
if($path.Length -eq 0)
{
Write-Verbose "No Path provided, assigning current location to path."
$currentPath = (Get-Item .\).FullName
}
else
{
$currentPath = $path
}
}
Process
{
try
{
Write-Verbose "Getting folder IO object for $currentPath"
$folderInfo = New-Object IO.DirectoryInfo($currentPath)
Write-Verbose "Getting the Folder Access Control List."
$folderACLs = $folderInfo.GetAccessControl()
Write-Verbose "Enabling Inheritance in ACL Object."
$folderACLs.SetAccessRuleProtection($false,$false)
Write-Verbose "Attempting to save the changes."
$folderInfo.SetAccessControl($folderACLs)
}
catch
{
Write-Verbose "There was an error adding the permissions."
Write-Error $Error[0]
}
}
}
Function #2
function Disable-AclInheritanceOnFolder
{
<#
.SYNOPSIS
This function will turn off inheritance on the folder
.DESCRIPTION
This function will turn off inheritance on the folder provided, currenth path if no path is provided.
It will also require that you specify if the current rules should be kept and converted or if they
should be removed.
.EXAMPLE
Disable-AclInheritanceOnFolder -path 'C:\TestPath' -ConvertRules $true|$false
.EXAMPLE
Disable-AclInheritanceOnFolder -ConvertRules $true|$false
.PARAMETER Path
The path of the folder where the ACL should be added.
.PARAMETER ConvertRules
Bool to know if the current rules should be converted and kept or removed from the folder.
If you remove the rules you might be loose access to the folder, be sure to take ownership of the
folder first.
#>
[CmdletBinding()]
[OutputType([int])]
Param
(
#Path
[Parameter(Mandatory=$false,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='What is the path where inheritance should be disabled?')]
[Alias('Location')]
[ValidateLength(3,250)]
[string]$path,
#PreserveInheritance
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='Should the current rules be removed or converted?')]
[Alias('PreserveInheritance')]
[bool]$RemoveCurrentRules
)
begin
{
if($path.Length -eq 0)
{
Write-Verbose "No Path provided, assigning current location to path."
$currentPath = (Get-Item .\).FullName
}
else
{
$currentPath = $path
}
}
Process
{
try
{
Write-Verbose "Getting folder IO object for $currentPath"
$folderInfo = New-Object IO.DirectoryInfo($currentPath)
Write-Verbose "Getting the Folder Access Control List."
$folderACLs = $folderInfo.GetAccessControl()
Write-Verbose "Enabling Inheritance in ACL Object."
$folderACLs.SetAccessRuleProtection($true,$true)
Write-Verbose "Attempting to save the changes."
$folderInfo.SetAccessControl($folderACLs)
}
catch
{
Write-Verbose "There was an error adding the permissions."
Write-Error $Error[0]
}
}
}
Function #3
function Add-AclToFolder
{
<#
.SYNOPSIS
This function will add an Group to a folder's ACL.
.DESCRIPTION
This function will add the given SecurityGroup or user name to the specified folder.
.EXAMPLE
Add-ACL -Path 'C:\TestPath' -securityGroup 'DL-SECURITYGROUP-NAME'
.PARAMETER Path
The path of the folder where the ACL should be added.
.PARAMETER securityGroup
The security group name
.PARAMETER AccessLevel
The access level that you wish to give to the group. Choose between ReadAndExecute, Modify, FullControl
#>
[CmdletBinding()]
[OutputType([int])]
Param
(
#Path
[Parameter(Mandatory=$false,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='What is the path where this group should be added?')]
[Alias('Location')]
[ValidateLength(3,250)]
[string]$path,
#securityGroup
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='What is the name of the group?')]
[Alias('group')]
[ValidateLength(3,50)]
[string]$securityGroup,
#AccessLevel
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='Access Level: ReadAndExecute, Modify, FullControl')]
[Alias('acl')]
[ValidateLength(3,15)]
[string]$accessLevel
)
begin
{
Write-Verbose "Starting Add-AclToFolder Function."
if($path.Length -eq 0)
{
Write-Verbose "No path was provided. We are getting the current path."
$currentPath = (Get-Item .\).FullName
}
else
{
$currentPath = $path
}
}
Process
{
#region Add-ACL
Write-Verbose "Process has started."
try
{
Write-Verbose "Getting folder IO object for $currentPath"
$folderInfo = New-Object IO.DirectoryInfo($currentPath)
Write-Verbose "Getting the Folder Access Control List."
$folderACLs = $folderInfo.GetAccessControl()
Write-Verbose "Creating new Security.AccessControl.FileSystemAccessRule."
Write-Verbose "Security Group: $securityGroup"
Write-Verbose "Access Level: $accessLevel"
$newACL = New-Object System.Security.AccessControl.FileSystemAccessRule("$($securityGroup)",$accessLevel,"ContainerInherit, ObjectInherit", "None", "Allow")
Write-Verbose "Adding the new Rule to the ACL object."
$folderACLs.AddAccessRule($newACL)
Write-Verbose "Attempting to save the changes."
$folderInfo.SetAccessControl($folderACLs)
}
catch
{
Write-Verbose "There was an error adding the permissions."
Write-Error $Error[0]
}
}
}
Function #4
function Remove-AclFromFolder
{
<#
.SYNOPSIS
This function will remove an Group or User from a folder's ACL.
.DESCRIPTION
This function will remove an Group or User from a folder's ACL. If no path is provided the script will use the current path.
.EXAMPLE
Remove-AclFromFolder -Path 'C:\TestPath' -securityGroup 'DL-SECURITYGROUP-NAME'
.EXAMPLE
Remove-AclFromFolder -securityGroup 'DL-SECURITYGROUP-NAME'
.PARAMETER Path
The path of the folder where the ACL should be removed.
#>
[CmdletBinding()]
[OutputType([int])]
Param
(
#Path
[Parameter(Mandatory=$false,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='What is the path where th group should be removed from?')]
[Alias('Location')]
[ValidateLength(3,250)]
[string]$path,
#securityGroup
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
HelpMessage='What is the name of the group?')]
[Alias('group')]
[ValidateLength(3,50)]
[string]$securityGroup
)
begin
{
Write-Verbose "Starting Add-AclToFolder Function."
if($path.Length -eq 0)
{
Write-Verbose "No path was provided. We are getting the current path."
$currentPath = (Get-Item .\).FullName
}
else
{
$currentPath = $path
}
}
Process
{
#region Add-ACL
Write-Verbose "Process has started."
try
{
Write-Verbose "Getting folder IO object for $currentPath"
$folderInfo = New-Object IO.DirectoryInfo($currentPath)
Write-Verbose "Getting the Folder Access Control List."
$folderACLs = $folderInfo.GetAccessControl()
Write-Verbose "Finding the rule to remove."
$aclToRemove = $folderACLs.Access | ?{$_.IdentityReference -match $securityGroup}
Write-Verbose "Removing $($aclToRemove.identityreference) from the ACL Object"
$folderACLs.RemoveAccessRule($aclToRemove)
Write-Verbose "Attempting to save the changes."
$folderInfo.SetAccessControl($folderACLs)
}
catch
{
Write-Verbose "There was an error modifying the permissions."
Write-Error $Error[0]
}
}
}
I believe that I been able to properly document the functions so there shouldn't be any confusion, but do let me know if you find any issues, comments or complaints.
Kind regards,
Me.
Monday, March 16, 2015
PowerShell ISE Cut (Ctrl + X)
Hello reader,
I know its been a while since I posted anything but things have been a little dull and haven't had anything worth posting. Today was a bit different though, I encountered a quirky bug, and thought I could share it.
I saw one of the comments by 'Scott - Oregon' in which he stated that VNC Viewer was causing the issue and closing it would resolve the problem. I don't use VNC Viewer, but I did remember earlier while working with mRemoteNG that I accidentally clicked to remote into a server with VNC instead of RDP, so I closed mRemoteNG and voila it started working.
I made sure to sign up and drop a comment on the Microsoft Connect post as it is still an active post.
I hope this might help someone out there!
Kind regards,
Me
Tuesday, January 6, 2015
Exchange cmdlet: Get-User
Hello!
Its been a bit since I posted last mainly because I was out on vacations. I been back for a few days now but it had been a bit uneventful. Until today when I was tasked with creating a termination script for over 300 users. I was provided with a list and started working on writing a script that followed our procedures. I don't think I can go into details for privacy reasons but we make some changes to the settings on our Exchange side when we terminate the user, and i noticed that some of the users that I was provided were not Mailbox users but MailUsers and they even threw a few MailContacts in there too.
The command Get-Mailbox does not work for MailUsers or MailContact and they each have their own. I did some digging around to try to find the best way to identify the type of mailbox they are before trying to use the 'Get-' or the 'Set-' commands but I wasn't able to find much. I even reviewed all of the properties for Get-ADUser and Get-ADObject hoping to find anything that would identify all three of them without having to write extra code - I don't normally like to try to write extra code unless I believe its completely necessary. Unfortunately none of it brought me the answer I was seeking.
It wasn't until I was going through the cmdlets that are added with the Exchange Add-in that I found the cmdlet 'Get-User'. I been writing PowerShell for over 2 years now, and quite franky I've never had never seen this particular cmdlet, but it really did made everything so much easier.
Syntax:
The regular output is:
PS C:\> get-user Jonatan.Bernal
Name RecipientType
---- -------------
Jonatan Bernal UserMailbox
It can if you format-list you get the full object: Deserialized.Microsoft.Exchange.Data.Directory.Management.User
The information provided is quite thorough and I don't have to bother what type of mailbox it is which quite frankly I find very useful to only use 1 cmdlet and use the other ones only when they are needed.
I hope that this might help someone out there.
Feel free to leave me a comment and let me know if this was helpful or know any other interesting cmdlets!
Kind regards,
Me
Update: well it was pointed out to me by +Lincoln Reedy that the cmdlet that I shared about would unfortunately not work for MailContacts, which again can be a problem. He also shared with me the cmdlet 'Get-Recepient' which would work for any type of object. I haven't quite worked much with this new cmdlet yet, so I'm still doing some research because I saw that you can use an authentication type of federation, so I'm wondering if you can actually get recipients outside of your organization. I'll update when I have more information on this.
Its been a bit since I posted last mainly because I was out on vacations. I been back for a few days now but it had been a bit uneventful. Until today when I was tasked with creating a termination script for over 300 users. I was provided with a list and started working on writing a script that followed our procedures. I don't think I can go into details for privacy reasons but we make some changes to the settings on our Exchange side when we terminate the user, and i noticed that some of the users that I was provided were not Mailbox users but MailUsers and they even threw a few MailContacts in there too.
The command Get-Mailbox does not work for MailUsers or MailContact and they each have their own. I did some digging around to try to find the best way to identify the type of mailbox they are before trying to use the 'Get-' or the 'Set-' commands but I wasn't able to find much. I even reviewed all of the properties for Get-ADUser and Get-ADObject hoping to find anything that would identify all three of them without having to write extra code - I don't normally like to try to write extra code unless I believe its completely necessary. Unfortunately none of it brought me the answer I was seeking.
It wasn't until I was going through the cmdlets that are added with the Exchange Add-in that I found the cmdlet 'Get-User'. I been writing PowerShell for over 2 years now, and quite franky I've never had never seen this particular cmdlet, but it really did made everything so much easier.
Syntax:
Get-User [-Identity <UserIdParameter>] <COMMON PARAMETERS>
Get-User [-Anr <String>] <COMMON PARAMETERS>
SourceCOMMON PARAMETERS: [-AccountPartition <AccountPartitionIdParameter>][-Arbitration <SwitchParameter>][-AuditLog <SwitchParameter>][-ConsumerNetID <NetID>][-Credential <PSCredential>][-DomainController <Fqdn>][-Filter <String>][-IgnoreDefaultScope <SwitchParameter>][-Organization <OrganizationIdParameter>][-OrganizationalUnit <OrganizationalUnitIdParameter>][-PublicFolder <SwitchParameter>][-ReadFromDomainController <SwitchParameter>][-RecipientTypeDetails <RecipientTypeDetails[]>][-ResultSize <Unlimited>][-SoftDeletedUser <SwitchParameter>][-SortBy <String>]
The regular output is:
PS C:\> get-user Jonatan.Bernal
Name RecipientType
---- -------------
Jonatan Bernal UserMailbox
It can if you format-list you get the full object: Deserialized.Microsoft.Exchange.Data.Directory.Management.User
The information provided is quite thorough and I don't have to bother what type of mailbox it is which quite frankly I find very useful to only use 1 cmdlet and use the other ones only when they are needed.
I hope that this might help someone out there.
Feel free to leave me a comment and let me know if this was helpful or know any other interesting cmdlets!
Kind regards,
Me
Update: well it was pointed out to me by +Lincoln Reedy that the cmdlet that I shared about would unfortunately not work for MailContacts, which again can be a problem. He also shared with me the cmdlet 'Get-Recepient' which would work for any type of object. I haven't quite worked much with this new cmdlet yet, so I'm still doing some research because I saw that you can use an authentication type of federation, so I'm wondering if you can actually get recipients outside of your organization. I'll update when I have more information on this.
Tuesday, December 16, 2014
Permissions
So I worked on this script for a few hours yesterday
The script is intended to go through every path in a directory and get all of the permissions
of the folders, and export them into a CSV. Surprisingly enough, the script itself
works great too; however, i came to the sad problem of paths being too long and
not getting all of the permissions.
I've looked at this from a long of angles and feel like I've ran out of Google power
here. If someone has an idea of how to get this done, that doesn't include
running a Robocopy first to get the paths. Please share with me.
Kind regards,
Me.
$drive
= "F:\"
$fileName
= "C:\Audits\FDrive_Audit_$((Get-Date -Format d).Replace(" ","_").replace("/","-").Replace(":",'-')).csv"
$ACL_Report
= @()
$Stack
= New-Object
System.Collections.Stack
function
getPermissions($folder)
{
$ACL_Report = @()
foreach($reference
in (Get-ACL
$folder |
%{$_.Access}))
{
$aclObj =
New-Object psobject
$aclObj |
Add-Member -MemberType
NoteProperty -Name
'Path' -Value
$folder
$aclObj |
Add-Member -MemberType
NoteProperty -Name
'Account' -Value
$reference.IdentityReference
$aclObj |
Add-Member -MemberType
NoteProperty -Name
'Access' -Value
$reference.FileSystemRights
$aclObj |
Add-Member -MemberType
NoteProperty -Name
'Inherited' -Value
$reference.IsInherited
$aclObj |
Add-Member -MemberType
NoteProperty -Name
'Inheritance' -Value
$reference.InheritanceFlags
$aclObj |
Add-Member -MemberType
NoteProperty -Name
'Propagation' -Value
$reference.PropagationFlags
$ACL_Report += $aclObj
}
$ACL_Report += " "
$ACL_Report | Export-Csv $fileName -NoTypeInformation
-Append
}
function
create-Queue($currentFolder)
{
foreach($folder
in (Get-ChildItem
$currentFolder -Directory))
{
getPermissions $folder.FullName
$Stack.Push($folder.FullName)
create-Queue $stack.Pop()
}
}
create-Queue
$drive
Friday, November 14, 2014
PowerShell and Scheduled Tasks
I have been setting up some schedule PowerShell scripts through the Task Scheduler; however, I was having a bit of trouble with one of the scripts.
The script would run perfectly if I ran it manually, but when I ran the task nothing would happen. As you might know this is a bit of a problem because schedule tasks don't not show the console, and won't allow you to see the errors. The Task's log are not very helpful either.
What helped me troubleshoot the problem is this little cmdlet:
Start-transcript -path C:\Temp\Filename.txt
Placing that command at the beginning of your script will create a transcript file. The transcript file will contain everything that would print into the console, and it should look a little like this:
-------------------------------------------------------------
**********************
Windows PowerShell transcript start
Start time: 20141114101902
Username : DOMAIN\S.AD.Util
Machine : HOSTNAME (Microsoft Windows NT 6.3.9600.0)
**********************
Transcript started, output file is C:\Temp\Transcript_11-14-2014.txt
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 1.0 tmp_scev4zye.pet {Get-DServerSetti...
-------------------------------------------------------------
I hope this might help someone out there!
The script would run perfectly if I ran it manually, but when I ran the task nothing would happen. As you might know this is a bit of a problem because schedule tasks don't not show the console, and won't allow you to see the errors. The Task's log are not very helpful either.
What helped me troubleshoot the problem is this little cmdlet:
Start-transcript -path C:\Temp\Filename.txt
Placing that command at the beginning of your script will create a transcript file. The transcript file will contain everything that would print into the console, and it should look a little like this:
-------------------------------------------------------------
**********************
Windows PowerShell transcript start
Start time: 20141114101902
Username : DOMAIN\S.AD.Util
Machine : HOSTNAME (Microsoft Windows NT 6.3.9600.0)
**********************
Transcript started, output file is C:\Temp\Transcript_11-14-2014.txt
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 1.0 tmp_scev4zye.pet {Get-DServerSetti...
-------------------------------------------------------------
If there is any errors they will show here, even if they are not stopping errors. Which is great because at one point my script was sending the email and successfully completing, but failing to create the report all together and sending a blank email.
I hope this might help someone out there!
Wednesday, July 23, 2014
C# Learning - Creating new AD accounts
I've been coding in PowerShell for 2 years now, and I gotta say switching over to C# is a nightmare! I do like it though, its has been a great fun experience. Once I got past the whole "Hello world" tutorials and learning the syntax it got a lot more fun. I'm not that I'm an expert in any way, but I believe I'm starting to get a hang of what is going on, which makes me happy.
Today as part of my on going project I had to create a function to create AD users through C#, and I'm using System.DirectoryServices class which actually requires that you add each property to the user, but doesn't actually tell you what does properties are, so after some looking around I found a table in this article. It made it a lot simpler than trying to guess the names. Here is the table for those that just want to get a quick look:
I removed the Ads because I'm not sure if they would affect his stuff.
Today as part of my on going project I had to create a function to create AD users through C#, and I'm using System.DirectoryServices class which actually requires that you add each property to the user, but doesn't actually tell you what does properties are, so after some looking around I found a table in this article. It made it a lot simpler than trying to guess the names. Here is the table for those that just want to get a quick look:
LDAP Attribute | Example |
| C | Country: e.g GB for Great Britain. |
| CN - Common Name | CN=Guy Thomas. Actually, this LDAP attribute can be made up from givenName joined to SN. |
| CN | Maps to 'Name' in the LDAP provider. Remember CN is a mandatory property. See also sAMAccountName. |
| description | What you see in Active Directory Users and Computers. Not to be confused with displayName on the Users property sheet. |
| displayName | displayName = Guy Thomas. If you script this property, be sure you understand which field you are configuring. DisplayName can be confused with CN or description. |
| DN - also distinguishedName | DN is simply the most important LDAP attribute. CN=Jay Jamieson, OU= Newport,DC=cp,DC=com |
| givenName | Firstname also called Christian name |
| homeDrive | Home Folder : connect. Tricky to configure |
| initials | Useful in some cultures. |
| name | name = Guy Thomas. Exactly the same as CN. |
| objectCategory | Defines the Active Directory Schema category. For example, objectCategory = Person |
| objectClass | objectClass = User. Also used for Computer, organizationalUnit, even container. Important top level container. |
| physicalDeliveryOfficeName | Office! on the user's General property sheet |
| postOfficeBox | P.O. box. |
| profilePath | Roaming profile path: connect. Trick to set up |
| sAMAccountName | This is a mandatory property, sAMAccountName = guyt. The old NT 4.0 logon name, must be unique in the domain. |
| sAMAccountName | If you are using an LDAP provider 'Name' automatically maps to sAMAcountName and CN. The default value is same as CN, but can be given a different value. |
| SN | SN = Thomas. This would be referred to as last name or surname. |
| title | Job title. For example Manager. |
| userAccountControl | Used to disable an account. A value of 514 disables the account, while 512 makes the account ready for logon. |
| userPrincipalName | userPrincipalName = guyt@CP.com Often abbreviated to UPN, and looks like an email address. Very useful for logging on especially in a large Forest. Note UPN must be unique in the forest. |
| wWWHomePage | User's home page. |
Examples of Exchange Specific LDAP attributes | |
| homeMDB | Here is where you set the MailStore |
| legacyExchangeDN | Legacy distinguished name for creating Contacts. In the following example, Guy Thomas is a Contact in the first administrative group of GUYDOMAIN: /o=GUYDOMAIN/ou=first administrative group/cn=Recipients/cn=Guy Thomas |
| An easy, but important attribute. A simple SMTP address is all that is required billyn@ourdom.com | |
| mAPIRecipient - FALSE | Indicates that a contact is not a domain user. |
| mailNickname | Normally this is the same value as the sAMAccountName, but could be different if you wished. Needed for mail enabled contacts. |
| mDBUseDefaults | Another straightforward field, just the value to:True |
| msExchHomeServerName | Exchange needs to know which server to deliver the mail. Example: /o=YourOrg/ou=First Administrative Group/cn=Configuration/cn=Servers/cn=MailSrv |
| proxyAddresses | As the name 'proxy' suggests, it is possible for one recipient to have more than one email address. Note the plural spelling of proxyAddresses. |
| targetAddress | SMTP:@ e-mail address. Note that SMTP is case sensitive. All capitals means the default address. |
| showInAddressBook | Displays the contact in the Global Address List. |
| c | Country or Region |
| company | Company or organization name |
| department | Useful category to fill in and use for filtering |
| homephone | Home Phone number, (Lots more phone LDAPs) |
| l (Lower case L) | L = Location. City ( Maybe Office |
| location | Important, particularly for printers and computers. |
| manager | Boss, manager |
| mobile | Mobile Phone number |
| ObjectClass | Usually, User, or Computer |
| OU | Organizational unit. See also DN |
| pwdLastSet | Force users to change their passwords at next logon |
| postalCode | Zip or post code |
| st | State, Province or County |
| streetAddress | First line of address |
| telephoneNumber | Office Phone |
| userAccountControl | Enable (512) / disable account (514) |
»
| |
Examples of Obscure LDAP Attributes | |
| dNSHostname | |
| rID | |
| url | |
| uSNCreated, uSNChanged | |
I removed the Ads because I'm not sure if they would affect his stuff.
Here is the difference in code from creating users in PowerShell and in C#:
C# * Please note that I am passing the variables from the "OnClick" function for a button, and also that all the properties name are not provided to you as they are in PowerShell. Final note there is some parameters that have not yet been used as they will be added at a later point when I create the mailbox.
Edit >
It seems that I forgot a simple o in the Country property. (see in bold)
PowerShell * In this particular example I'm taking the values from a CSV, which allows me to create multiple accounts very quickly.
//This is needed
Import-Module ActiveDirectory
New-ADUser -AccountPassword (ConvertTo-SecureString -AsPlainText "PASSWORDHERE" -Force) -Server 'DCHOSTNAME' `
-Enabled $true `
-Name $file.username
`
-GivenName $file.name `
-Surname $file.lastname
`
-Initials $file.middle
`
-DisplayName $file.displayname
`
-SamAccountName $file.username
`
-Office $file.office
`
-Department $file.Department
`
-Company $file.company
`
-StreetAddress $file.Street
`
-City $file.city `
-State $file.state `
-PostalCode $file.postalcode
`
-Country $file.country
`
-Description $file.description
`
-Path $file.path `
-UserPrincipalName $file.userprincipalname
`
-EmailAddress $file.userprincipalname
`
-OtherAttributes @{'co'="United
States"; 'countryCode'="840"}
|
//These are required
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
public void createUser(int ticketnumber, string firstname, string middleIn, string lastName,
string samaccountname, string email, string telephone, string hemisphere, string company,
string office, string address, string city, string state, string division, string Code,
string OrganizationalUnit, string country, string department, string title, string displayName,
string postalCode, string co, string Manager)
{
string path = "LDAP://" +
OrganizationalUnit;
int NORMAL_ACCOUNT = 0x200;
int PWD_NOTREQD = 0x20;
try
{
using (DirectoryEntry ou = new DirectoryEntry(path))
{
DirectoryEntry user =
ou.Children.Add("CN=" + samaccountname, "user");
user.Properties["SamAccountName"].Add(samaccountname);
user.Properties["userPrincipalName"].Add(samaccountname + "@DOMAIN");
user.Properties["name"].Add(firstname
+ " " + lastName);
user.Properties["givenName"].Add(firstname);
user.Properties["initials"].Add(middleIn);
user.Properties["SN"].Add(lastName);
user.Properties["telephoneNumber"].Add(telephone);
user.Properties["company"].Add(company);
user.Properties["physicalDeliveryOfficeName"].Add(office);
user.Properties["streetAddress"].Add(address);
user.Properties["l"].Add(city);
user.Properties["st"].Add(state);
user.Properties["co"].Add(country);
user.Properties["C"].Add(co);
user.Properties["department"].Add(department);
user.Properties["title"].Add(title);
user.Properties["userAccountControl"].Value = NORMAL_ACCOUNT | PWD_NOTREQD;
user.Properties["description"].Add("AC #" +
ticketnumber + " JB | Created with
JBSoftware");
user.Properties["displayName"].Add(displayName);
user.Properties["objectCategory"].Add("PERSON");
user.Properties["postalCode"].Add(postalCode);
user.Properties["manager"].Add(Manager);
user.CommitChanges();
}
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
MessageBox.Show(E, "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
} }
|
Well I think that is it for the day, I hope that this information might be useful to someone out there!
Edit >
It seems that I forgot a simple o in the Country property. (see in bold)
Subscribe to:
Posts (Atom)