我正在尝试对 ActiveDirectory 计算机对象所属的组进行排序。为了获取组列表,我使用以下代码(在本例中为 PC123
):
Get-adcomputer 'PC123' -properties Memberof | Select-Object -ExpandProperty 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
我尝试使用 Sort-Object 进行排序:
Get-adcomputer 'PC215' -properties Memberof | Select-Object -ExpandProperty MemberOf | Sort-Object -Property Memberof
不幸的是,输出保持不变。我尝试通过更改 Sort-Object -Property Memberof
的位置来玩弄一下,但这似乎不是问题。任何提示将不胜感激。
最佳答案
您正在尝试根据不再存在的属性 (MemberOf
) 对数组
进行排序,在这种情况下您不应该不 使用-Property
。
使用该对象作为示例:
$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
值得添加 official documentation 中的这句话因为它与问题相关:
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.
关于powershell - 通过 Powershell 对 AD 对象的属性进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70455444/