Home > Blockchain >  Sorting properties of an AD-object via Powershell
Sorting properties of an AD-object via Powershell

Time:12-24

I'm trying to get the groups an ActiveDirectory Computer-Object belongs to sorted. To get the group listing I use the following code (in this case for PC123):

Get-adcomputer 'PC123' -properties Memberof | Select-Object -ExpandProperty MemberOf

I get the following output and as expected the groups are not sorted:

CN=(A) Group3,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local
CN=(A) Group1,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local
CN=(A) Group4,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local
CN=(A) Group2,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local

I tried to sort using Sort-Object:

Get-adcomputer 'PC215' -properties Memberof | Select-Object -ExpandProperty MemberOf | Sort-Object -Property Memberof

Unfortunately the output stays the same. I tried fooling around a bit by changing the position of Sort-Object -Property Memberof but that does not seem to be the problem. Any hints would be appreciated.

CodePudding user response:

You're trying to sort an array based on a property (MemberOf) that is not there anymore, in this case you should not use -Property.

Using this object as example:

$computer = [pscustomobject]@{
    Name     = 'PC215'
    MemberOf = @(
        'CN=(A) Group3,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local'
        'CN=(A) Group1,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local'
        'CN=(A) Group4,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local'
        'CN=(A) Group2,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local'
    )
}
PS /> $computer | Select-Object -Expand MemberOf | Sort-Object -Property MemberOf

CN=(A) Group3,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local
CN=(A) Group1,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local
CN=(A) Group4,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local
CN=(A) Group2,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local

PS /> $computer | Select-Object -Expand MemberOf | Sort-Object

CN=(A) Group1,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local
CN=(A) Group2,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local
CN=(A) Group3,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local
CN=(A) Group4,OU=OU-Path1,OU=OU-Path2,DC=domain,DC=local

Worth adding this quote from the official documentation since it's related to the question:

If sort properties are not included in a command, PowerShell uses default sort properties of the first input object. If the type of the input object has no default sort properties, PowerShell attempts to compare the objects themselves.

  • Related