在特定列上对数组排序的问题。
[PSObject[]]$arr = @()
$arr += [PSObject]@{
who = 'z';
what = 'snake';
where = 'c1';
when = 'd1'
}
$arr += [PSObject]@{
who = 'z';
what = 'beer';
where = 'c1';
when = 'd1'
}
$arr += [PSObject]@{
who = 'a';
what = 'snake';
where = 'c1';
when = 'd1'
}
$arr += [PSObject]@{
who = 'b';
what = 'ape';
where = 'c1';
when = 'd1'
}
$arr | Sort-Object what
输出:
Name Value ---- ----- where c1 who a when d1 what snake where c1 who b when d1 what ape where c1 who z when d1 what snake where c1 who z when d1 what beer
因此未按“什么”排序。
有什么想法吗?
答案 0 :(得分:0)
将哈希表投射到[PSObject]
并没有达到您的期望。 PSObject
已经是您要定义的哈希表的基本类型,因此您的代码仅创建哈希表列表,而不创建自定义对象列表。要从哈希表创建自定义对象,请改用PSCustomObject
类型的加速器(需要PowerShell v3或更高版本,在旧版本中请使用New-Object
cmdlet)。
演示:
PS C:\> $ht = @{'a'='b'; 'c'='d'} PS C:\> $ht.GetType().FullName System.Collections.Hashtable PS C:\> $ht.PSBase.GetType().FullName System.Management.Automation.PSObject PS C:\> $ht Name Value ---- ----- c d a b PS C:\> $o1 = [PSObject]$ht PS C:\> $o1.GetType().FullName System.Collections.Hashtable PS C:\> $o1.PSBase.GetType().FullName System.Management.Automation.PSObject PS C:\> $o1 Name Value ---- ----- c d a b PS C:\> $o2 = [PSCustomObject]$ht PS C:\> $o2.GetType().FullName System.Management.Automation.PSCustomObject PS C:\> $o2.PSBase.GetType().FullName System.Management.Automation.PSObject PS C:\> $o2 c a - - d b