powershell - 组对象 AsHashTable 不适用于 ScriptProperty

标签 powershell group-object

作品:

$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/

相关文章:

PowerShell - 组对象性能不佳

powershell - 在powershell中静默注册GAC目录下的所有dll

powershell - 添加-AzureAccount : Federated service - Error: ID3242

powershell - 从 TFS 获取多版本差异报告?

azure - 您的 Azure 凭据尚未设置或已过期,请运行 Connect-AzAccount 来设置您的 Azure 凭据

powershell - HDInsight powershell 作业提交无法使用流式 C# 作业定义自定义 libjar

powershell - PowerShell:导入CSV文件,计数组大小和输出到原始文件,并在计数后添加新列

Powershell 仅当基于列 1 的组的列 2 -cge 列 3 时才显示行