Bam Madrigan
Bam Madrigan

Reputation: 1

Powershell - Ad user from OU to Security groups if not members of several groups

I'm writing a script to check if user from specific OU are not members of Group 1 or Group 2 or Group 3 or Group 4.

I have try this but some users are getting listed while they are not suppose to be.

get-aduser -filter * -searchbase "$Ou" | where-object {((get-aduser $_.samaccountname -properties memberof).memberof -ne "$grp1") -or ((get-aduser $_.samaccountname -properties memberof).memberof -ne "grp2") -or ((get-aduser $_.samaccountname -properties memberof).memberof -ne "grp3") -or ((get-aduser $_.samaccountname -properties memberof).memberof -ne "grp4")} | Select SamAccountName

Upvotes: 0

Views: 337

Answers (1)

mike crowley
mike crowley

Reputation: 66

Not sure I follow, but it sounds like you're asking for something like this:

$ou = 'OU=crowleytest,DC=contoso,DC=local'
$group1 = 'CN=group1,OU=crowleytest,DC=contoso,DC=local'
$group2 = 'CN=group2,OU=crowleytest,DC=contoso,DC=local'
$group3 = 'CN=group3,OU=crowleytest,DC=contoso,DC=local'
$group4 = 'CN=group4,OU=crowleytest,DC=contoso,DC=local'

$users = Get-ADUser -SearchBase $ou -Filter * -Properties memberof

$results = $users | where {
    $_.memberof -notcontains $group1 -and
    $_.memberof -notcontains $group2 -and
    $_.memberof -notcontains $group3 -and
    $_.memberof -notcontains $group4
}

$results

e - This filter could also be moved to the left into the -filter parameter for better performance, but that requires a different syntax. If you're not working with a huge list of users, the example above should suffice.

Upvotes: 1

Related Questions