Get AD Users NOT members of any specified groups

Hello,

I am trying to retrieve a list of all users that are NOT a member of any of specified groups (11 total).
I am able to get a list of users that are a member of each group, but am having trouble getting users that do not belong to any of the specified groups.

The desired output should be a list of DisplayName, Office, memberof

Any assistance would be much appreciated, below is the code I have so far…

$FWGroups = (get-adgroup -Filter "name -like '*FW Policy*'")
$FWGroupMembers = foreach($group in $FWGroups){Get-ADGroupMember -Identity $group | Select Name, @{Label="Group Name";Expression={$group}}}

$AllUsers = Get-ADUser -Filter * -Properties DisplayName,Office,memberof
$NonFWGroupMembers = Get-ADUser -Filter * -Properties DisplayName,Office,memberof | Where-Object {$AllUsers -notin $FWGroupMembers}

$NonFWGroupMember

I cannot check at the moment but something like this should be enough I think:

$FWGroups = (Get-ADGroup -Filter "name -like '*FW Policy*'").DistinguishedName
$AllUsers = Get-ADUser -Filter * -Properties DisplayName, Office, memberof
$NonFWGroupMembers = 
  $AllUsers | 
    Where-Object { 
      -not (Compare-Object -ReferenceObject $FWGroups -DifferenceObject $_.MemberOf -IncludeEqual -ExcludeDifferent)
    }

The attribute MemberOf contains an array of the distinguished names of the groups an AD user is member of. So you can compare this array agains a list of distinguished names of groups you specified.

And BTW: When you post code you should format it as code please

Guide to Posting Code

I would simplify by using the SamAccountName or DistinguishedName and just find all users not in the list of all FWGroupMembers

$FWGroups = (get-adgroup -Filter “name -like ‘*FW Policy*'”)

$FWGroupMembers = foreach($group in $FWGroups){
    Get-ADGroupMember -Identity $group | Select SamAccountName, Name, @{Label=”Group Name”;Expression={$group}}
}

$NonFWGroupMembers = Get-ADUser -Filter * -Properties DisplayName,Office,memberof |
    Where-Object SamAccountName -NotIn $FWGroupMembers.samaccountname | Select-Object DisplayName, Office, memberof

… “simplify” ??? :wink: Why is this simpler? You query the AD once for the desired groups and once for ALL AD users … just like me. Then you compare the users against the members of the groups. … just another way around I’d say. :wink: