Getting Domain from DN

by Oct 22, 2013

A "DN" (Distinguished Name) is the path to an Active Directory object and could look similar to this:

'CN=Tobias,OU=Authors,DC=powershell,DC=local'

To get just the domain part of a DN, use code like this:

$DN = 'CN=Tobias,OU=Authors,DC=powershell,DC=local'
$pattern = '(?i)DC=\w{1,}?\b'

([RegEx]::Matches($DN, $pattern) | ForEach-Object { $_.Value }) -join ',' 

This piece of code uses a regular expression to find all DC= parts of a DN; then joins them together using a comma as delimiter.

The result would be: DC=powershell,DC=local

Twitter This Tip! ReTweet this Tip!