Process multiple ObjectCategory values using Get-ADObject cmdlet

Welcome Forums General PowerShell Q&A Process multiple ObjectCategory values using Get-ADObject cmdlet

This topic contains 3 replies, has 3 voices, and was last updated by

 
Member
4 years, 2 months ago.

  • Author
    Posts
  • #18954

    Participant
    Points: 1
    Rank: Member

    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

    Keymaster
    Points: 1,673
    Helping HandTeam Member
    Rank: Community Hero

    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

    Participant
    Points: 1
    Rank: Member

    Okay, that is what I thought.

    Thanks DJ, I appreciate it brother.

  • #18960

    Member
    Points: 0
    Rank: Member

    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 *
    

The topic ‘Process multiple ObjectCategory values using Get-ADObject cmdlet’ is closed to new replies.