【发布时间】:2021-04-06 08:31:54
【问题描述】:
我是 PowerShell 的新手,从 Python 背景中快速学习它。
我正在从另一个通过 REST 调用检索数据的工具中提取数据。
METERS 变量以这种格式存储在源中。
{
"500 HR": 500,
"1000 HR": 1000,
"2000 HR": 2000
}
PowerShell 代码
#REST call to source
$meter=@{}
Foreach ($item in $origresult.Items) {
$result = (Invoke-RestMethod -Uri $url -Headers $headers -Method GET -ContentType application/json -ErrorVariable RespErr)
$meter.Add($item.Name,$result.Value)
}
Write-Host ($meter | Out-String) -ForegroundColor Red
这是输出
Name Value
---- -----
LastUploaded 2020-12-29T06:38:02
IsEnabled 1
METERS {...
ORGID WHS
如何检索 METERS 并遍历字典?到目前为止我试过这个。 Python 以其简单的数据结构宠坏了我,PowerShell 并不是那么简单,除非有更简单的方法来做到这一点。
$mymeters = $meter.METERS | ConvertFrom-Json
Write-Host ($mymeters | Out-String) -ForegroundColor Yellow
输出
500 HR : 500
1000 HR : 1000
2000 HR : 2000
这是我迄今为止尝试过的一些东西 -
$mymeters = [ordered]@{}
" Here is the item $mymeters.Get_Item(500 HR)" #my silly attempt!
# Looping is a no go either - it says specialized ordered dictionary
foreach ($ind in $mymeters) {
" --> $ind"
}
输出
Here is the item System.Collections.Specialized.OrderedDictionary.Get_Item(500 HR)
--> System.Collections.Specialized.OrderedDictionary
我可能遗漏了一些真正基本的东西,但我无法自己弄清楚!非常感谢任何帮助。我想要的只是遍历 METERS 哈希表/字典并调用一个函数。
【问题讨论】:
标签: python powershell dictionary hashtable powershell-5.0