Hi All,
How can I filter out or exclude some of the results of the Get-ADObject with the below Query?
Script:
$Exclusions = @(
'SystemMailbox',
'HealthMailbox',
'Migration'
'Delete'
'Disabled'
)
Get-ADObject -Filter '(ObjectClass -eq "user" -or ObjectClass -eq "computer") -and Enabled -eq $true -and isRecycled -eq $false -and name -ne "Deleted Objects"' | Where-Object{$_.Name -notin $Exclusions}
Issues:
-
When I add the Filter Enabled -eq $true, nothing is returned. How can I get only the enabled AD Objects?
-
I wanted to exclude certain OU like ‘OU=Disabled Users’
-
If the name contains anything like the above $Exclusions
Thank you in advance.
Enabled
is not an attribute of Get-ADObject
output. You will need to look at UserAccountControl
attribute instead if you are sticking with that cmdlet.
You can use -not UserAccountControl -band 2
in place of Enabled -eq $true
.
Comparison operators for collections like -contains
, -notcontains
, -notin
, and -in
compare single strings to a collection. Exact matches are required, i.e. no wildcards are allowed. If you want to do wildcard matching, consider using a regex operator like -notmatch
. First you will need to use alternations (|
) to create the OR-like
condition.
Excluding an OU will likely require parsing the DistinguishedName
value. I don’t believe that attribute is recognized in the -Filter
so Where-Object
must be used.
$Exclusions = 'SystemMailbox', 'HealthMailbox', 'Migration', 'Delete','Disabled'
$regex = $Exclusions -join '|'
Get-ADObject -Filter “(ObjectClass -eq ‘user’ -or ObjectClass -eq ‘computer’) -and -not UserAccountControl -band 2 -and isRecycled -eq ‘$false’ -and name -ne ‘Deleted Objects’” | Where-Object { $.Name -notmatch $regex -and $.DistinguishedName -notlike “OU=Disabled Users”}