Parsing Distinguished Names

by | September 8,2017

Table of Contents

Using Split() for Parsing Distinguished Names

Distinguished names are strings, and strings contain powerful ways of parsing data. The most powerful yet simple approach is the Split() method.

Extracting the Last Element with Split()

Check out how easy it is to get back the name of the last element of a distinguished name using Split():

$dn = 'CN=pshero010,CN=Users,DC=powershell,DC=local'
$lastElement = $dn.Split(',')[0].Split('=')[-1]
$lastElement

Split() always produces a string array. With brackets, you can access individual array elements. So the code first splits by comma, then takes the first element which is “CN=pshero010”. Next, use the same technique again, and split by “=”. Here, we are interested in the last array element. PowerShell supports negative array indices which count from the array end, so index -1 retrieves the last array element. Mission accomplished.

Twitter This Tip! ReTweet this Tip!