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