Reputation: 741
I have this PS query to get the Distinguishedname of servers:
$AD = get-adcomputer -filter {OperatingSystem -like '*Server*' -and OperatingSystem -notlike '*2003*'} -property name, description, DistinguishedName | Select name, description, DistinguishedName
and I want to get the first instance of the OU, so I want "OU=Web Servers"
CN=Server1,OU=Web Servers,OU=Servers,OU=HeadOffice Servers,etc
How can I do this? Thanks
Upvotes: 0
Views: 8560
Reputation: 1
The regular expression solution provided works only if the first element is not OU. Here is a solution that will work in any scenario and is a bit more readable for the non-regex types. If you have the following example the splitting by "," or the regular expression solution will return 'OU=Servers', 'Servers" respectively ( I assume you want to have the OU= removed from the string )
$dn = 'OU=Web Servers,OU=Servers,OU=HeadOffice Servers,DC=domaain,DC=com'
($dn -split 'OU=|,OU=')[1]
If you don't have nested OUs then you might need to add some additional logic
(($dn -split 'OU=|,OU=')[1] -split ',')[0]
Upvotes: 0
Reputation: 68311
Parsing DNs by splitting on commas is a fairly common practice, but can be unreliable because the names can contain embedded commas (they'll be escaped with a backslash). Here's a regular expression solution that should be more reliable:
$dn = 'CN=Server1,OU=Web Servers,OU=Servers,OU=HeadOffice Servers,DC=domaain,DC=com'
$OU = $dn -replace '.+?,OU=(.+?),(?:OU|DC)=.+','$1'
$OU
Web Servers
Upvotes: 1
Reputation: 13227
If you split the DN string and use the comma as the seperator, the OU will then be the second element in the array.
This can then be returned using square brackets to access an individual element of the array. As it's the second element we use [1] to access it, as [0] is the first element.
$DN = "CN=Server1,OU=Web Servers,OU=Servers,OU=HeadOffice Servers,DC=This,DC=Com"
$DN.Split(",")[1]
Upvotes: 0