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
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