Foreach-object manipulation

Hi.

May be someone could help me in my problemm :slight_smile:

I have $userAD.Properties.memberof

PS C:\Users\renat> $userAD.Properties.memberof
CN=Support Team,OU=AD-Groups,OU=lala,DC=lala,DC=com
CN=User Support Team,OU=AD-Groups,OU=lala,DC=lala,DC=com
CN=Test,OU=ServiceAndGroups,DC=lala,DC=com
CN=TestHR,OU=ServiceAndGroups,DC=lala,DC=com
CN=TestPR,OU=ServiceAndGroups,DC=lala,DC=com

I need to create $adGroups where be presented cn names of the groups that start with Test

$adGroups = $userAD.Properties.memberof | ForEach-Object ??? | Where-Object {$_.StartsWith(“Test”)}

the result should be like this:

PS C:\Users\renat> $userGroups
Test
TestHR
TestPR

Hi, welcome to the forum :wave:

Firstly, when posting code in the forum, please can you use the preformatted text </> button. It really helps us with readability, and copying and pasting your code (we don’t have to faff about replacing curly quote marks to get things working). If you can’t see the </> in your toolbar, you will find it under the gear icon.

How to format code on PowerShell.org

Filter the groups with Where-Object.
Split the string for the remaining groups on ‘,OU=’ and select the first element in the array of split strings (element 0).
Remove CN=

$adGroups = $userAD.Properties.MemberOf | 
    Where-Object {$_ -like 'CN=Test*'} | 
        ForEach-Object {($_ -split ',OU=')[0] -replace 'CN='}

matt-bloomfield/ thank you for the answer.

I will take into account your remark regarding formatting the text.

The script you provided works, thank you very much.