作品:
$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
最佳答案
您无法通过 prop 名称或基于键的访问访问哈希表中的值的原因是键/props 包装在 PSObjects 中。有一个 Github issue在 Powershell Core 中修复此问题,但它可能会永远保留在 Windows Powershell 中。
如果您想在分组后转换为哈希表,并希望通过属性名称或基于键的访问来访问某些分组值,请执行以下操作:
$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']
如果你想在分组后转换为哈希表,并想一次访问所有分组的值,请执行以下操作:
$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
如果您在分组后不转换为哈希表,并且想要访问 $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
关于powershell - 组对象 AsHashTable 不适用于 ScriptProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61564401/