Process multiple ObjectCategory values using Get-ADObject cmdlet

I would like to get output for multiple “ObjectCategory” values using the Get-ADObject cmdlet and it doesn’t work if I create an array as in the following example:

$Object = @(“computer”, “group”)

foreach ($item in $object)
{
Get-ADObject -Filter ‘ObjectCategory -eq $Object’ -Properties CanonicalName |
Select-Object -Property @{N=“Name”; E={$.Name}},
@{N=“AD Path”;E={($
| Select-Object -ExpandProperty CanonicalName) }} |
Format-List -Property *
}

However, if I do this, it works fine for just one value for the $Object variable:

$Object = “Computer”

foreach ($item in $object)
{
Get-ADObject -Filter ‘ObjectCategory -eq $Object’ -Properties CanonicalName |
Select-Object -Property @{N=“Name”; E={$.Name}},
@{N=“AD Path”;E={($
| Select-Object -ExpandProperty CanonicalName) }} |
Format-List -Property *
}

Can someone please help explain why this is?

Thank you very much

The -Filter parameter is processed at the DC - and the DC isn’t capable of handling variables. Further, the DC can’t process an array. You’d need to run this as multiple queries, or construct a much more complex LDAP query involving OR clauses.

Okay, that is what I thought.

Thanks DJ, I appreciate it brother.

You should be able to construct a filter with multiple checks on object categories joined by -or . (You can do this in the LDAP filter syntax, or with -Filter; whatever your preference.) If you want to write a function that accepts an array, this filter string can be constructed dynamically:

$Object = @("computer", "group")
$filter = ($Object | ForEach-Object { "objectCategory -eq '$_'" }) -join ' -or '

Get-ADObject -Filter $filter -Properties CanonicalName |
Select-Object -Property 'Name', @{N="AD Path";E={($_.CanonicalName) }} |
Format-List -Property *