首页 > 解决方案 > 如何使用等于命令在powershell中创建foreach循环

问题描述

我开始学习 PowerShell 并一直在尝试创建一个 foreach 循环,以便如果其中一个 JSON 项的状态不是 STARTED,它会使用其名称作为可执行命令中的变量来运行命令。这是我的 json txt 文件的样子;

{
  "UNIT": {
    "name": "AB",
    "address": "fadasdaer",
    "status": "MIA"
  },
  "UNIT": {
    "name": "CD",
    "address": "fadasdahsfaaer",
    "status": "STARTED"
  },
    "UNIT": {
    "name": "EF",
    "address": "9afahegt",
    "status": "DEAD"
  }
}

而我想要做的是从 my 中读取json.txt它并让它运行一个 foreach 循环并执行一个命令,其中名称包含在命令中。我目前有这样的东西,但我的 PowerShell 理解有限,它不起作用......

$JSON = json.txt
$check = $JSON | ConvertFrom-Json
$started=STARTED

foreach($unit in $check.unit){
    if ($unit.status -notmatch $started) {
    $name=$unit.name
    executable.exe start $name
    }

}

任何指导将不胜感激。

标签: arraysjsonpowershell

解决方案


您的主要问题是您的 JSON 格式错误:它定义了一个对象,然后多次UNIT定义了它的属性。

您应该将其定义为数组:注意封闭的顶级[...]和缺少UNIT属性:

[
  {
    "name": "AB",
    "address": "fadasdaer",
    "status": "MIA"
  },
  {
    "name": "CD",
    "address": "fadasdahsfaaer",
    "status": "STARTED"
  },
  {
    "name": "EF",
    "address": "9afahegt",
    "status": "DEAD"
  }
]

纠正了 JSON 输入和其他语法问题:

$JSON = 'json.txt'
$check = Get-Content -Raw $JSON | ConvertFrom-Json
$started = 'STARTED'

foreach ($unit in $check) {
  if ($unit.status -notmatch $started) {
    $name = $unit.name
    executable.exe start $name
  } 
}

如果您无法从源头修复 JSON,则可以在其传递给之前自行对其进行转换ConvertFrom-Json

$check = (Get-Content -Raw $JSON) `
  -replace '\A\{', '[' `
  -replace '\}\Z', ']' `
  -replace '"UNIT": ' | ConvertFrom-JSON

推荐阅读