使用 PowerShell splatting 对属性进行排序

Sorting properties with PowerShell splatting

我正在使用 Active Directory module for Windows PowerShell 从 Active Directory 导出某些值。如何以与列出的属性相同的顺序显示结果?当我 运行 这个命令时,我得到了按字母顺序列出的所有可用属性。但我想要和期望的是只获得我在哈希 table 中列出的属性,其顺序与哈希 table.

相同
$GetADUserOptions = @{
    properties = @(
    "employeeID",
    "employeeNumber",
    "whencreated",
    "wWWHomePage",
    "c",
    "CO"
    )
}
Get-ADUser @GetADUserOptions

我错过了什么?

您无法控制 Active Directory 或模块返回给您的属性的顺序。

但是如果您对结果数据所做的操作是导出到 CSV 之类的东西(或者甚至只是控制台)并且您关心列的顺序,只需使用 Select-Object 和您想要的顺序在进行导出之前。

您可以像这样按照@AdminOfThings 的建议从 splat 传递数组

Get-ADUser @GetADUserOptions | Select-Object $GetADUserOptions.properties

或者您可以显式地执行此操作,这也允许某些 post 处理默认情况下人类可读性不高的属性,例如 lastLogonTimestamppwdLastSet

# assuming lastLogonTimestamp was added to your list of properties
Get-ADUser @GetADUserOptions | Select-Object sAMAccountName,@{
    Label='LastLogonTS'
    Expression={
        [DateTime]::FromFiletime($_.lastLogonTimestamp)
    }
}