Getting a List of User with more than 2 roles that start the same

im trying to get a list of User with more than 2 roles which start the same. My script looks like this.

`Import-Module ActiveDirectory

Get-ADUser -Filter * -Properties memberOf |`

$.memberof -like '*abc*’ -and
$_.memberof.count -ge 2 } |

Format-List -Property Name | Out-File -FilePath C:\Users\Powershell\Desktop\Users.txt`

It does not work, because the Where Object memberof.count filters for all roles and not for the ones starting with “abc_”.

Thank you for your help


Welcome to the forum. :wave:t4:

When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.
Thanks in advance
How to format code in

You need to expand the multivalued property before you can count the values:

$SearchBase = 'OU=Berlin,OU=Germany,OU=Europe,DC=contoso,DC=com'
Get-ADUser -Filter * -Properties MemberOf -SearchBase $SearchBase |
    Where-Object {
        ($_.MemberOf | Where-Object {$_ -like '*abc*'}).count -gt 1
    } |
        Select-Object -Property Name |
            Out-File -FilePath 'C:\Users\Powershell\Desktop\Users.txt'

Regardless of that - foramt cmdlets like Format-List are build to display information on the console only. So if you want to add further steps you should never use format cmdlets.

Thank you, now it works.
Do i need to go via $SearchBase or can i just go via Get-ADuser -Filter * -Properties MemberOf?
Is there any specific reason to search/indicate for the location?

You don’t need to but it is highly recommended because you put a lot less stress on your AD when you specify a search base. :wink: