Friday 6 June 2014

Powershell - get domain from distinguishedname

Had problems finding this little nugget of Powershell before...

So I am noting this down here for simplicity when I come to need it again...

$dn = "cn=name,ou=oulocation,dc=domain,dc=local"

$domain = $dn -Split "," | ? {$_ -like "DC=*"}
$domain = $domain -join "." -replace ("DC=", "")
Write-Host $domain

The above is setting an example $dn but will probably be grabbed by another bit of code elsewhere...

then split the DN on , and only get the bits that start DC=something
then join the output together with a . in between, then get rid of DC= that lingers behind so you end up with: domain.local

Hope this helps other people out there with a similar query!