PowerShell, check for user in group RRS feed

  • Question

  • I am working on a script to remove a user from every instance of a specific named group across all sites.

    In testing, I have created two user objects, one by $group.users.getbyemail(email) and one from $web.ensureuser("domain\user"), and have tried testing for membership in a group using various comparison operators. All return false, though I checked to see that the user was indeed in the group, and the one user object was created with the GetByEmail method from that group.

    I would think that $user -in $group.Users or $group.Users -contains $user would return true, but, clearly, I am mistaken. Any suggestions would be most welcome.

    I suppose I can user the GetByEmail method and then test that the user object is not null, but that seems less clean.

    Thursday, January 26, 2017 7:58 PM


  • Looks like it's cleaner to flip that logic on its head.

    Instead of checking $group.Users to see if it contains $user, check $user.Groups and see if it contains a group with the specified name.

    $user = $web.EnsureUser("domain\user")
    $match = $user.Groups | where{ $_.Name -eq $groupName}

    • Edited by thriggle Thursday, January 26, 2017 9:44 PM
    • Marked as answer by oldamigauser Monday, January 30, 2017 8:35 PM
    Thursday, January 26, 2017 9:44 PM

All replies