Home > Enterprise >  Using Regex and PowerShell, I am trying to retrieve users Full name from the DistinguishedName attri
Using Regex and PowerShell, I am trying to retrieve users Full name from the DistinguishedName attri

Time:09-29

I am trying to use Regex to retrieve the full name of the user. So if I return the DistinguishedName of a user, I want the string between "CN=" and the first ",". For example if I use the ActiveDirectory Powershell module:

$disName = (get-aduser -identity mySamAccountName -Properties Distinguishedname).Distinguishedname

the output would be

CN=MyFirstname MyLastname,OU=Parent,OU=Child,DC=DomainControler,DC=com

I want the string "MyFirstname MyLastname" using regex. I found a horrible solution to even look at it hurts my eyes but I know regex is better I just cant figure out how to use it to target the string between CN= and ,

# My Solution. Hard on the eyes :-(
$fullname = $dishName.substring($dishName.IndexOf("=")   1, $dishName.IndexOf(",") - 3).trim()

Please help me with regex as an effective tool...

CodePudding user response:

You're looking for the cn attribute ("Common Name"):

$disName = (Get-ADUser -Identity mySamAccountName -Properties cn).cn
  • Related