如何使用 PowerShell 从数组 JSON 中的对象获取键值?

How to get key value from object inside array JSON using PowerShell?

我正在尝试从 JSON 数组中的对象获取键值,如果我需要更改我的 RuleId 键结构,请提出建议,下面是我想要的输出

rule = 1300
rulevalue = false
    
rule = 1304
rulevalue = true

JSON 文件

{
    "Rule": [{
        "MPName": "ManagementPackProject",
        "Request": "Apply",
        "Category": "Rule",
        "RuleId": {
            "1300": "false",
            "1304": "true"
        }
    }]
}

PowerShell

$Content = Get-Content -Raw -Path "C:\temp\Rule.json" | ConvertFrom-Json -ErrorAction Stop
$Content = $Content.Rule | Where-Object { $_.Request -eq "Apply" }

foreach($item in $Content.RuleId)
{
    rule = $item.key
    rulevalue = $item.value
    
    process...
}

你在找这样的东西吗?

$JSON = @'
    {
        "Rule": [{
            "MPName": "ManagementPackProject",
            "Request": "Apply",
            "Category": "Rule",
            "RuleId": {
                "1300": "false",
                "1304": "true"
            }
        }]
    }
'@

$Content = $JSON | ConvertFrom-Json
$Content = $Content.Rule | Where-Object Request -eq 'Apply'

$Output = foreach( $Rule in $Content.RuleId.psobject.Properties ) {
    [PSCustomObject]@{
        Rule = $Rule.Name
        RuleValue = $Rule.Value
    }
}
$Output | Format-List

输出:

Rule      : 1300
RuleValue : false

Rule      : 1304
RuleValue : true