I was voluntold to learn powershell about a week ago, and learned a lot from here. I was unable to find a method that worked for me so now I am posting my first question.
I am looking to output under the OU column, not the full DistinguishedName, but a piece of it only.
How would I assign specific part of the DistinguishedName to the OU? Instead of "CN=,OU=,DC=*", I would only want "(Name of OU) under (Name of Parent OU)"
Input
$ADExtProps =
@(
'Enabled',
'SamAccountName',
'OU'
)
Get-ADUser -Filter * -SearchBase $TestOU -Properties $ADExtProps
Format-Table $ADExtProps -AutoSize -Wrap
Output
Enabled SamAccountName OU
------- -------------- --
True testuser04 {}
True testuser05 {}
True testuser01 {}
True testuser02 {}
True testuser03 {}
True testuser06 {}
True testuser07 {}
True testuser08 {}
True testuser09 {}
False testuser10 {}
Thank you!
How would I assign specific part of the DistinguishedName to the OU? Instead of "CN=,OU=,DC=*", I would only want "(Name of OU) under (Name of Parent OU)"
It could be done with regex extracting the OU name from the user's DistinguishedName
however for the sake of not overcomplicating it, you can first query all OUs using Get-ADOrganizationalUnit
then those objects already have the OU .Name
which you can use to construct your output:
Get-ADOrganizationalUnit -Filter * | ForEach-Object {
$ouName = $_.Name
Get-ADUser -Filter * -SearchBase $_.DistinguishedName -SearchScope OneLevel |
Select-Object Enabled, SamAccountName, @{N='OU'; E={ $ouName }}
}
If you want to extract the OU common name using regex the following should work:
$TestOU = 'OU=someOU,DC=someDomain,DC=com'
$re = [regex] '(?<=OU=).+?(?<!\\)(?=,)'
Get-ADUser -Filter * -SearchBase $TestOU |
Select-Object Enabled, SamAccountName, @{N='OU'; E={ $re.Match($_.DistinguishedName).Value }}