Process multiple ObjectCategory values using Get-ADObject cmdlet

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 2 years, 2 months ago.

  • Author
    Posts
  • #18954
    Profile photo of I Am Sir Ask Alot
    I Am Sir Ask Alot
    Participant

    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

  • #18955
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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.

  • #18959
    Profile photo of I Am Sir Ask Alot
    I Am Sir Ask Alot
    Participant

    Okay, that is what I thought.

    Thanks DJ, I appreciate it brother.

  • #18960
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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 *
    

You must be logged in to reply to this topic.