Home > other >  Trying to extract a list from AD that contains all of my users, in exception to one OU named Disable
Trying to extract a list from AD that contains all of my users, in exception to one OU named Disable

Time:03-06

This is what I have so far:

Get-ADUser -Filter 'Department -like "*"' -Properties * |
    Select -Property DisplayName,GivenName,Surname,Title,Department,Office,OfficePhone |
    Export-CSV "C:\ad-users.csv"

CodePudding user response:

I believe you could do it this way using -LDAPFilter, first you need to query the OU to Exclude and get it's DistinguishedName then you can query all users and filter them where their DistinguishedName does not contain the OU to exclude.

NOTE: This assumes there is only 1 OU with Name Disabled Users. If there are more OUs with the same I would recommend you to hardcode the DistinguishedName of the excluded OU in $ouDN.

It's also worth noting that querying all attributes (-Properties *) for all users is highly inefficient, you should always query only the attributes of interest (-Properties attrib1, attrib2, etc).

$properties = @(
    'DisplayName'
    'GivenName'
    'Surname'
    'Title'
    'Department'
    'Office'
    'OfficePhone'
)
$ouToExclude = 'Disabled Users'
$ouDN = (Get-ADOrganizationalUnit -LDAPFilter "(Name=$ouToExclude)").DistinguishedName
Get-ADUser -LDAPFilter "(Department=*)" -Properties $properties | & {
    process {
        if($_.DistinguishedName -notlike "*$ouDN") { $_ }
    }
} | Select-Object $properties | Export-Csv "C:\ad-users.csv" -NoTypeInformation

CodePudding user response:

You can use a Where-Object clause to filter on the users OU

# fill in the DistinguishedName of the 'Disabled Users' OU here
$ouToExclude = 'OU=...'

# Get-ADUser by default returns these properties:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
# so you only need to ask for extra properties not already in this list
Get-ADUser -Filter "Department -like '*'" -Properties DisplayName,Title,Department,Office,OfficePhone |
Where-Object { $_.DistinguishedName -notlike "*$ouToExclude" } | 
Select-Object DisplayName,GivenName,Surname,Title,Department,Office,OfficePhone |  
Export-Csv "C:\ad-users.csv" -NoTypeInformation
  • Related