Export users (CSV) - but exclude users that are members of a specific group

I have a PowerShell script that I’ve been using to spit out a CSV of all users in a specific OU, but I want to exclude users that are a member of a specific security group. Basically, all the users exist in the same OU otherwise I could choose which OU to pull from.

The only unique factor is the group they are a member of. What could I use to exclude these users?

Would adding this to the ‘get-aduser’ line work?

groupattribute -notcontains "<groupname>"

Here is a section of the script

$csvdata = get-aduser -filter {enabled -eq $true -and EmailAddress -like "*@domain*" -and givenname -like "*" -and surname -like "*"} -searchbase "OU=#someOU,DC=#companyname#,DC=com" -properties mail,country,department |

new-object psobject -property @{
email = $_.mail
first_name = $_.givenname
last_name = $_.surname
group = $_.country
department = $_.department
} | select email,first_name,last_name,group,department 

$payload = "email,first_name,last_name,group,department`n"

# filter out problematic data
$csvdata = $csvdata | Where-Object { ($_.email -match '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b') } | Sort-Object * -Unique

$csvdata | ForEach-Object { 
$payload = [string]::Concat($payload, $_.email, ",")
$payload = [string]::Concat($payload, $_.first_name, ",")
$payload = [string]::Concat($payload, $_.last_name, ",")
$payload = [string]::Concat($payload, $_.group, ",")
# $payload = [string]::Concat($payload, $_.mobile, ",")
# $payload = [string]::Concat($payload, $_.alternate_email, ",")
# $payload = [string]::Concat($payload, $_.alternate_mobile, ",")
# $payload = [string]::Concat($payload, $_.sms_enabled, ",")
$payload = [string]::Concat($payload, $_.department, "`n")

Hello aparbatani23,

On the line #1 you are getting users and attributes. By default Get-ADUser gets only 10 basic attributes and you are adding 3 more (mail,country,department).

So every AD user object in your case contains 13 attributes:

  1. DistinguishedName
  2. Enabled
  3. GivenName
  4. Name
  5. ObjectClass
  6. ObjectGUID
  7. SamAccountName
  8. SID
  9. Surname
  10. UserPrincipalName
  11. Mail
  12. Country
  13. Department
And then on line #8 you are simply renaming country attribute to group. It does not contains Group Membership. ADUser object property which contains groups is memberOf.

You can use notcontains operator but keep in mind that memberof contains collection of Distinguished Names of AD Groups that user is part of.

In order for notcontains to work you need to use distinguished name of the group in your filter:

CN=<Group Display Name>,CN=Users,DC=domain,DC=local


Hope that helps.