【发布时间】:2019-12-16 21:26:06
【问题描述】:
我正在编写一个 PowerShell 脚本,它将读取一个具有不同部分的 json 文件,例如 job1、job2 等。现在我的目标是分别读取每个部分并将其作为键值对循环。我还需要维护输入文件的顺序,因为作业是按顺序安排的。这些作业将 json 文件中的值作为输入运行。
我尝试使用 Powershell 5.1 版,我在其中创建了 PSCustomObject,但顺序按字母顺序排序,这是我不想要的。
Json 文件:
{ "Job1": [
{
"Ram" : "India",
"Anthony" : "London",
"Elena" : "Zurich"
}],
"Job2": [
{
"Build" : "fail",
"Anthony" : "right",
"Sam" : "left"
}]}
$json = Get-Content -Path C:\PowershellScripts\config_File.json |
ConvertFrom-Json
$obj = $json.Job1
$json.Job1 | Get-Member -MemberType NoteProperty | ForEach-Object {
$key = $_.Name
$values = [PSCustomObject][ordered]@{Key = $key; Value = $obj."$key"}
$values
}
我希望按照 json 文件中提供的顺序分别循环遍历每个部分。例如,遍历 Job1 部分并以与 json 文件中相同的顺序仅获取值。
【问题讨论】:
-
您会考虑使用经典的 for 循环吗?
for($i=0;$i-lt $json.Job1.count;$i++){..your stuff here..}
标签: json powershell powershell-3.0