Get-ADUser filter out specific OU, custom column

MNEsther picture MNEsther · Aug 3, 2015 · Viewed 50k times · Source

trying to get an Audit report of active users. We have an OU that I do not want to report on.

Give me all the active (enabled) AD accounts. EXCEPT in a specific OU.

Get-ADUser -Filter{enabled -eq $true} | Select-object Samaccountname,surname,givenname `
        | Export-Csv -NoTypeInformation C:\scripts\ActiveUsers.csv

How can I filter out OU=Service Accounts?

I also need to have a custom column in Column A of the csv output. Example: The word "ACME" in column A in all rows.

Thanks much Esther

Answer

Mathias R. Jessen picture Mathias R. Jessen · Aug 3, 2015

Filter on parent containers

The OU is part of the object's DistinguishedName property.

Use Where-Object to filter out objects that reside inside a certain OU by removing the first part of the DistinguishedName and comparing the rest with the DistinguishedName of the OU:

$OUDN = "OU=Service Accounts,OU=Accounts,DC=domain,DC=tld"
Get-ADUser -Filter {Enabled -eq $true} | Where-Object { $_.DistinguishedName -notlike "*,$OUDN" }

If you know the OU name, but not the full DistinguishedName, you can remove immediate child objects of the OU from the results by splitting the distinguished name into compartments and comparing the second one (the immediate parent container) to the name you want to exclude:

$OUName = "Service Accounts"
Get-ADUser -Filter {Enabled -eq $true} | Where-Object {
    $ObjectCN,$ParentCN,$null = $_.DistinguishedName -split "(?<=[^\\]),"
    $ParentCN -ne "OU=$OUName"
}

or exclude any object with the given OU name in its ancestral path:

$OUName = "Service Accounts"
Get-ADUser -Filter {Enabled -eq $true} | Where-Object {
    $ObjectCN,$ParentCNs = $_.DistinguishedName -split "(?<=[^\\]),"
    $ParentCNs -notcontains "OU=$OUName"
}

Custom property values

Select-Object supports calculated properties. You can supply a calculated property with a static expression as the first property to select, like so:

Get-ADUser | Select-Object @{Name="MyCustomColumn";Expression={"ACME"}},Name

Exported to a CSV, the above example would have the colunm headers "MyCustomColumn" and "Name" in col A and B respectively, col A holding the value "ACME" always, whereas col B would hold the individual Names of the users