组对象 AsHashTable 不适用于 ScriptProperty

Group-Object AsHashTable doesn't work for ScriptProperty

作品:

$Names = 1..5 | % { new-object psobject | add-member -Type NoteProperty -Name Name -Value "MyName" -PassThru } | group Name -AsHashTable
$Names.MyName

无效:

$Names = 1..5 | % { new-object psobject | add-member -Type ScriptProperty -Name Name -Value {"MyName"} -PassThru } | group Name -AsHashTable
$Names.MyName

您无法通过道具名称或基于键的访问访问哈希-table 中的值的原因是 keys/props 包装在 PSObjects 中。在 Powershell Core 中有一个 Github issue 来修复这个问题,但它可能会永远保留在 Windows Powershell 中。

如果您想在分组后转换为散列-table,并希望通过 属性 名称或基于键的访问来访问某些分组值,请执行以下操作:

$Names = 1..5 | ForEach-Object { 
    New-Object PsObject | Add-Member -Type ScriptProperty -Name Name -Value { return "MyName"} -PassThru 
} | Group-Object -Property 'Name' -AsHashTable -AsString
$Names.MyName 
$Names['MyName'] 


如果要在分组后转换为散列-table,并希望一次访问所有分组值,请执行以下操作:

$Names = 1..5 | ForEach-Object { 
    New-Object PsObject | Add-Member -Type ScriptProperty -Name Name -Value { return "MyName"} -PassThru 
} | Group-Object -Property 'Name' -AsHashTable
$Names.Values


如果您在分组后不转换为散列-table,并且想要访问 $Names.Group 中的数据,则需要扩展 属性。

$Names = 1..5 | % { 
    new-object psobject | add-member -Type ScriptProperty -Name Name -Value {"MyName"} -PassThru 
} | Group-Object -Property 'Name' 
$Names | Select-Object -ExpandProperty Group