string method "contains" reports 'false'

Welcome Forums General PowerShell Q&A string method "contains" reports 'false'

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
1 year, 1 month ago.

  • Author
    Posts
  • #84338

    Participant
    Points: 22
    Rank: Member

    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

  • #84343

    Participant
    Points: 263
    Helping Hand
    Rank: Contributor

    "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.

  • #84353

    Participant
    Points: 321
    Helping Hand
    Rank: Contributor

    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

  • #84389

    Participant
    Points: 22
    Rank: Member

    Excellent – now it makes sense.
    Thanks!

The topic ‘string method "contains" reports 'false'’ is closed to new replies.