Query users not in a groups - using Powershell

 A weird question I was asked today, can I get a list of users not in a group, caught me off guard as people usually need to know who is a member of a group, not who is not in a group.....

PowerShell to the rescue, shared for your convenience....

$groups = 'Group1', 'Group2', 'Group3'

$whereFilter = $groups | Foreach-Object { 

    $g = (Get-ADGroup $_).DistinguishedName

    "{0} '{1}'" -f '$_.memberOf -notcontains',$g 

}

$whereFilter = [scriptblock]::Create($whereFilter -join " -and ")

$users = (Get-ADUser -filter {objectclass -eq "user"} -properties memberof).where($whereFilter)

$users | Select-Object SamAccountName,DistinguishedName |

    Export-Csv Temp.csv -NoTypeInformation -Encoding UTF8

This will return a CSV for your Excel excitement.





Previous Post Next Post

نموذج الاتصال