简体   繁体   中英

if user is in ADGroup evaluating incorrectly powershell

Im trying to keep and AD group to date with an sql database table. but i cannot get my logic to work correctly, here is a sample of what i mean:

    $group = "<ADGroupName>"
    $user = (Get-ADUser -Identity <sAMAccountName> -Properties MemberOf,sAMAccountName | Select-Object MemberOf,sAMAccountName)

    Function Add-ADUserToGroup{
        if ($user.MemberOf -notmatch $group){
            Add-ADGroupMember -Identity $group -Members $user.sAMAccountName
            }
        else{
            Wirte-Host "User is already a member of $group"
            }
        }

    Add-ADUserToGroup

if i put my sAMAccountName in the $user variable set, and if i exist the group specified in the $group variable, it still attempts to add me to group and fails because i already exist in the group. i have tried other operands in place of the -notmatch such as -notin -ne but nothing seems to evaluate the if statement correctly and im not sure why. Thanks for any help.

Try this instead:

$group = "<ADGroupName>"
$user = (Get-ADUser -Identity <sAMAccountName> -Properties MemberOf,sAMAccountName | Select-Object MemberOf,sAMAccountName)

Function Add-ADUserToGroup{
    if (-not ($user.MemberOf -match $group)){
        Add-ADGroupMember -Identity $group -Members $user.sAMAccountName
        }
    else{
        Wirte-Host "User is already a member of $group"
        }
    }

Add-ADUserToGroup

You're doing a match against an array, and then casting the result as [bool] in the IF.

$user.MemberOf -notmatch $group is going to return all the groups the user is a member of that don't match $group . If that returns anything at all the result will be True for the IF, and it's probably always going to find some.

So, i found a solution, and it is in the operand. so if i use this:

if ($user.MemberOf -notmatch $group){
     <Foo>
     }

the if statement does not evaluate correctly at all, however if i use this:

if (!($user.MemberOf -match $group)){
     <Foo>
     }

the if statement does evaluate correctly. i don't have an explanation, but it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM