1

I am trying to strip Active Directory's "DistinguishedName" attribute down to just the most specific OU title. For example, I am given:

CN=Smith\, Tom,OU=Developers,OU=Users,DC=myOrganization,DC=com

And I want this reduced to:

Developers

I have tried doing this without success (assume the variable is storing the DistinguisedName as above):

$disName = $disName.Replace("CN(*)OU=", "")
$disName = $disName.Replace(",OU(*)=com", "")

These statements are making no change to the string.

I am new to using regex in Powershell so I assume I'm just making a syntax mistake but the concept is correct.

3 Answers 3

2

It's simpler to use a regular expression for this kind of data extraction, as others have already suggested, because String.Replace doesn't support things like non-greedy matches. I would recommend using a slightly more elaborate regular expression, though:

^.*?,\s*ou=(.*?),\s*(?:ou|dc).*$

because the suggestions you got so far will produce undesired results when the OU name contains characters like spaces or commas.

Demonstration:

PS C:\> $dn = 'CN=Smith\, Tom,OU=Developers\, Foo,OU=Users,DC=example,DC=com'
PS C:\> $dn -replace '^.*?,\s*ou=(.*?),\s*(?:ou|dc).*$', '$1'
Developers\, Foo
PS C:\> $dn -replace '^CN.*?OU=|,.*$'
Developers\
PS C:\> [regex]::Match($dn, 'OU=(\w+),').Groups[1].Value
Users
Sign up to request clarification or add additional context in comments.

Comments

0

You could use a regex:

$attribute = "CN=Smith\, Tom,OU=Developers,OU=Users,DC=myOrganization,DC=com"    
[regex]::Match($attribute, 'OU=(\w+),').Groups[1].Value

Output:

Developers

3 Comments

Thanks! Can you explain what (\w+) and Groups[1] are doing?
Explaination copied from regex101.com: /OU=(\w+),/ OU= matches the characters OU= literally (case sensitive) 1st Capturing group (\w+) \w+ match any word character [a-zA-Z0-9_] Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy] , matches the character , literally
Groups[1] selects the second group (containing the capturing group) from [regex]::Match()
0
^CN.*?OU=|,.*$

You can use this and replace by empty string.See demo.

https://regex101.com/r/rX1tE6/6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.