Simple code trying to pull the names of AD groups that a user belongs to:
Get-ADUser johndoe -Properties MemberOf
But what I get back is the full DN of each group, like this:
CN=APP_DUO_MFA_U,OU=Groups,OU=Accounts,OU=BH-ROOT,DC=bh,DC=contoso,DC=org,
All I want it to return is "APP_DUO_MFA_U". What am I doing wrong???
CodePudding user response:
You're not doing anything wrong, the memberOf field does indeed contain a list of DNs!
You can either do a second query against AD to resolve the target group's Name value:
$groupNames = (Get-ADUser johndoe -Properties memberOf).memberOf |Get-ADGroup |ForEach-Object Name
Or, if you just need the CN (which might well be the same as the Name) value, use the regex-based -replace operator to remove the RDN and everything from the first the first non-escaped comma:
$groupNames = (Get-ADUser johndoe -Properties memberOf).memberOf -replace '^CN=(.*?)(?<=[^\\]),.*$','$1'
CodePudding user response:
If you want to extract the CN value from a DN, an efficient way is to remove the unwanted strings.
# Using the -replace operator
(Get-ADUser johndoe -Properties MemberOf).MemberOf -replace '^CN=(.*?),[A-Z]{2}=.*$','$1'
# Using -split
(Get-ADUser johndoe -Properties MemberOf).MemberOf.foreach{
($_ -split ',?[A-Z]{2}=')[1]
}
Explanation:
For -replace, the goal is to remove the beginning CN= (^CN=). Then remove everything up until the next comma followed by either a domain component (DC=) or an organizational unit (OU=), which is matched by lazy match (.*?) and ,[A-Z]{2}=. .*$ matches the remaining characters until the end of the string. Since we used () around the lazy match, we can substitute it later as $1, which denotes capture group 1. In short, remove the entire DN and bring back just the part you want to see.
For -split, you will have to loop through each DN. The foreach() method or Foreach-Object will suffice. The code will split the string into the DN parts' values. The CN value will always be the second part, i.e. index 1.
