Get All Users Excluding an OU

Getting all the user in AD is quite easy but excluding an OU could be bit of a challenging.

The below script will be able to help you achieve you this.

$OUDN = "Organization Unit Distinguished name that you want to exclude"
$arr1 = @()

$pathtosave = "Save location .csv"

Add-Content -Path $pathtosave -Value '"Fist Name","Last Name","SAM Name","Description","OU"'


$arr1 += Get-ADUser -Filter {Enabled -eq $true} | select givenname,surname,samaccountname,Description,DistinguishedName | Where-Object { $_.DistinguishedName -notlike "*,$OUDN" }

foreach($unit in $arr1){
Add-Content -Path $pathtosave -value ($unit.givenname+","+$unit.surname+","+$unit.samaccountname+","+$unit.Description+","+$unit.DistinguishedName)
}

Published by iamfazul

Author of the site

Leave a comment