powershell - 通过 Powershell 对 AD 对象的属性进行排序

标签 powershell active-directory

我正在尝试对 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/

相关文章:

powershell - 远程 PowerShell 到 AzureRM 虚拟机

powershell - 移动项目 “the path is not supported.”

c# - 将 ActiveDirectory 与 ASP.NET 或 PHP 连接

c# - 如何注销除当前登录用户外的所有Windows 10用户?

powershell - 作为组托管服务帐户启动 PowerShell

powershell - 如何从SharePoint 2010工作流中调用可执行文件或Powershell脚本?

active-directory - NTLMv2 和 Kerberos 有什么区别?

c# - 在 asp.net MVC 中使用事件目录进行身份验证

active-directory - 在 Microsoft Active Directory 中搜索用于操作的 API

vb.net - 邮箱和 Active Directory 帐户创建自动化