0

good morning. i am trying to avoid GUI at my job to practice powershell and one of the daily tasks i have is to check if a user was added to the right groups so i was using the cmdlet:

get-aduser $username -Properties memberof | select -expand memberof

and im getting a list of the groups the user is in. but i get it like that :

CN=GroupName,OU=OU,OU=another OU,etc... 

and i want it just to output the CN value if i would have to do that in bash i would grep it, is there any way to "grep" in powershell? or isolate the CN so it would output only that?

1 Answer 1

1

Simple enough, just create a property in the Select part of your command as such:

get-aduser $username -Properties memberof | Select -expand memberof | select @{n='GroupName';e={$_.split(',')[0].Substring(3)}} -expand GroupName

That takes the Memberof property, splits it on commas, takes the first item in that split, and takes a substring of it skipping the first 3 characters. Then it assigns that value to the GroupName property, and expands that property.

Alternatively you can use a RegEx match, and return the matches in a ForEach loop.

get-aduser $username -Properties memberof | Select -Expand Memberof |Where{$_ -match "CN=(.*?),"} | ForEach{$Matches[1]}

Or parse the value in a ForEach loop using the same methods used in the first code.

get-aduser $username -Properties memberof | Select -expand memberof | ForEach {$_.split(',')[0].Substring(3)}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much for the quick response i found the second method you suggested as the one that suits me.
Nice, that's the one I regularly use as well. I'm a fan of the RegEx matches

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.