test if $variable -contains $variable2

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of David Schmidtberger David Schmidtberger 1 year, 4 months ago.

  • Author
  • #26618
    Profile photo of David Schmidtberger
    David Schmidtberger

    I'm trying to check against a list of group names (with associated text in secondary column) against a users group memberships
    input file would be 2 columns name,output
    ad group name in the first column, and some output text in the second.
    i can-not get -compare to work, it doesn't return anything.
    if i chang my list to put * before and after the group name in the input file i can use -like but this isn't very nice.
    what am i doing wrong with -contains

    $sam = Read-Host 'SamAccountName to check app groups?'
    $applist  = $path + "\applist.csv"
    $user = Get-ADUser $sam -Properties memberof|select -expand memberof
    $csv = import-csv $applist
    foreach($app in $csv)
    if ($user -contains $app.name)
    Write-Host "$($app.output) is the action"
  • #26622
    Profile photo of Dave Wyatt
    Dave Wyatt

    -contains doesn't do wildcard matching, and the MemberOf field in AD contains distinguished names. If your $app.name field was also a distinguished name, it would probably work.

    Try this instead, and see if it does the trick:

    if ($user -like "*$($app.name)*")

    In this case, because $user is an array, -like will function more like a filter (returning an array with all of the elements that matched the pattern). However, this is still fine for an If statement, since an empty array means $false, and if one or more strings are found that match the pattern, then it'll evaluate to $true.

  • #26625
    Profile photo of David Schmidtberger
    David Schmidtberger

    Thanks Dave, it was the "*$($app.name)*"

    i'd tried "*$app.name*" and got nowhere.

    much appreciated

You must be logged in to reply to this topic.