如何在powershell脚本中获取对象的键和值的数组?

Dja*_*ned 2 powershell powershell-2.0 powercli powershell-3.0

我有一个以下格式的对象数组

\n
$test = @(2 :{1,3,5}, 3 : {2,4,6})\n
Run Code Online (Sandbox Code Playgroud)\n

我想从 $test 数组中提取键和值的对象。

\n

这是我执行上述任务的 powershell 脚本,

\n
$testnumbers = @(2,3)\n$testStores = @{}\n$testInfo = $null\nforeach ($tn in $testnumbers) {\n    $testInfo = @{}\n    for($i=0;$i -lt $tn;$i = $i+1) {\n    $testPrompt = Read-Host -Prompt "Assign the test numbers"\n    $testInfo += $testPrompt\n    }\n$testInfoSet = {$tn = $testInfo}\n$testInfoObj = New-Object psobject \xe2\x80\x93Property $testInfoSet\n$testStores += $testInfoObj\n}\n
Run Code Online (Sandbox Code Playgroud)\n

请提供解决方案,先谢谢了!

\n

dno*_*dno 5

我想你可能想像这样设置你的哈希表......

$test = @{2 = (1,3,5); 3 = (2,4,6)}

foreach($item in $test.GetEnumerator()){
    echo $item.key
    echo $item.value
}
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句:虽然“Write-Output”(其内置别名是“echo”)是输出数据的正确工具,但您通常不需要显式使用它,因为 PowerShell 隐式地输出(到成功数据流) ) 任何未捕获或重定向的表达式或命令;例如,“$foo”本身与“Write-Output $foo”/“echo $foo”具有相同的效果。虽然使用“Write-Output”没有什么坏处,但请考虑展示 PowerShell 的隐式输出功能(可能带有解释性注释),以推广 PowerShell 惯用解决方案。 (3认同)
  • 很高兴听到我们同意,但我建议您实际上用这些信息更新您的答案,以造福未来的读者。完成此操作后,您可以将我的第一个评论和此评论标记为“不再需要”(或 ping 我,以便我可以自己删除它们)。 (2认同)