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

1 year, 4 months ago.

  • Author
  • #84338

    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':

    Hope someone can help.

  • #84343

    Points: 1,165
    Helping Hand
    Rank: Community Hero

    "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

    Points: 1,139
    Helping Hand
    Rank: Community Hero

    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

    # 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

    Points: 22
    Rank: Member

    Excellent – now it makes sense.

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

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort