MNEsther
MNEsther

Reputation: 111

Get-ADUser filter out specific OU, custom column

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

Upvotes: 3

Views: 56290

Answers (2)

MNEsther
MNEsther

Reputation: 111

This worked - thanks gang.

Get-ADUser -Filter {enabled -eq $true} | ? {$_.DistinguishedName -notlike "*,OU=Service Accounts,*"}

And the custom column:

Select-Object -Property @{n="ColumnA"; e={"ACME"}}

Upvotes: 6

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

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

Upvotes: 11

Related Questions