arrays - 如何使用等于命令在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
}
}
任何指导将不胜感激。
解决方案
您的主要问题是您的 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
推荐阅读
- .net - 为什么 NET 金融库使用双精度数?
- c# - 创建外键时实体框架中的验证错误
- mongodb - 使用 Logstash 在 Mongodb 和 ElasticSearch 之间同步数据
- sql - 是否可以选择找出具有重复数据的 spark 内部表列值
- r - 删除字符串中特定字符后的 n 个字符
- entity-framework-core - 从 dotnet CLI 搭建 oracle 数据库
- python - 如何在不破坏 RAM 的情况下附加这两个数组?
- javascript - 包含其他对象的 Joi 验证器对象
- android - 如何使用 kotlin 使用 android 设置默认相机
- rest - REST API - 请求参数中的特殊字符