如何指定Powershell列表属性的顺序

eh57zj3b  于 2023-01-20  发布在  Shell
关注(0)|答案(1)|浏览(108)

下面是一个简短的脚本,它给出了所讨论的行为的示例:

$foo = New-Object -TypeName PSCustomObject -Property @{
    Username = "BSmith"
    OU = "Finance"
    Department = "Finance"
    Description = "Accounts"
    Office = "345 2nd St"
    ServerName = "WFINANCE"
    ShareName = "BSmith$"
    LocalPath = "E:\Users\BSmith"
    }

Write-Host $foo

输出为:@{ServerName=WFINANCE; Office=345 2nd St; Username=BSmith; LocalPath=E:\Users\BSmith; OU=Finance; Description=Accounts; ShareName=BSmith$; Department=Finance}
正如你所看到的,变量输出的顺序和它们被指定时的顺序是不同的,为什么会这样,我怎样才能使顺序保持一致呢?
我只在一台计算机上测试过,但是在脚本的执行过程中,输出的顺序是一致的。在声明属性时,我对属性的顺序也没有什么影响。我无法测试并查看不同的计算机是否会返回不同的顺序。

axr492tv

axr492tv1#

预先将属性列表定义为[ordered]哈希表,然后从该哈希表创建对象:

$properties = [ordered]@{
  Username    = "BSmith"
  OU          = "Finance"
  Department  = "Finance"
  Description = "Accounts"
  Office      = "345 2nd St"
  ServerName  = "WFINANCE"
  ShareName   = "BSmith$"
  LocalPath   = "E:\Users\BSmith"
}
$foo = New-Object -TypeName PSCustomObject -Property $properties

请注意,这需要PowerShell v3或更高版本。

相关问题