Author Posts

November 15, 2017 at 10:21 pm

I'm trying to test if users are members of an AD group by expanding a user's group memberships and testing if it contains part of the group name. Unfortunately I keep getting 'false' results to the contains() method when I expect it to be 'true'.
Here's a snippet:
$grouplist=get-aduser JDoe -property * |select -expand memberof
This results in several lines of system.string text similar to the following:
CN=DataProductionSchedule,OU=Security Groups,OU=Tech,DC=Domain,DC=net
I would expect running the following line should report 'true' but it comes back as 'false':
$grouplist.contains("DataP")

Hope someone can help.
Thanks
LB

November 15, 2017 at 11:17 pm

"Contains" is not a string method. It checks if an array contains a given item (not just a part of an item). So if you like to use it this way you would have to put the complete distinguished name in it. Or you extract all CNs before checking the existence.

November 16, 2017 at 12:09 am

Don't use contains for this as Olaf points out. Use -like or RegEx matching.

$grouplist = 'CN=DataProductionSchedule,OU=Security Groups,OU=Tech,DC=Domain,DC=net',
'CN=Marketing,OU=Security Groups,OU=Tech,DC=Domain,DC=net',
'CN=HelpDesk,OU=Security Groups,OU=Tech,DC=Domain,DC=net'

($grouplist) -like '*DataP*'
# CN=DataProductionSchedule,OU=Security Groups,OU=Tech,DC=Domain,DC=net

($grouplist) -match'DataP'
# CN=DataProductionSchedule,OU=Security Groups,OU=Tech,DC=Domain,DC=net

But why are you doing it this way when there are built-in PoSH cmdlets that does this. Well, depending on what OS and PoSH version you are using.

# Get all AD groups and the members
ForEach ($GroupName in (Get-ADGroup -Filter *))
{
The "AD Group $GroupName.Name members are:"
Get-ADGroupMember -Identity $GroupName.Name | Select Name
"`n"
}

# Get users and their groups memberships
(Get-ADUser -Filter *) | % {
"`nThe user " + $_.SamAccountName + ', is in the following AD Groups: '
Get-ADPrincipalGroupMembership $_.SamAccountName |
Select Name,GroupCategory,GroupScope } |
Format-Table -AutoSize

November 16, 2017 at 7:00 pm

Excellent – now it makes sense.
Thanks!