Author Posts

September 20, 2014 at 9:23 pm

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

September 20, 2014 at 9:54 pm

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.

September 20, 2014 at 10:58 pm

Okay, that is what I thought.

Thanks DJ, I appreciate it brother.

September 21, 2014 at 4:30 am

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 *