You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell获取XML/JSON中特定值对应的节点路径

解决方案

方案1:直接处理原始XML(推荐,无需提前转格式)

你导出的XML文件可以直接用PowerShell解析,不需要额外转JSON,运行以下脚本即可得到符合要求的结果:

# 读取XML配置文件
[xml]$epConfig = Get-Content -Path "ExploitProtection.xml" -Raw

# 遍历所有应用配置节点
foreach ($app in $epConfig.SelectNodes("//AppConfig")) {
    $exeName = $app.Executable
    # 遍历当前应用下的所有缓解措施节点
    foreach ($mitigation in $app.ChildNodes) {
        if ($mitigation.NodeType -ne 'Element') { continue }
        $mitiName = $mitigation.LocalName
        $trueAttrs = @()
        # 遍历属性筛选值为true的项
        foreach ($attr in $mitigation.Attributes) {
            if ($attr.Value -eq 'true') {
                $trueAttrs += $attr.Name
            }
        }
        # 按要求格式输出
        if ($trueAttrs.Count -eq 1 -and $trueAttrs[0] -eq 'Enable') {
            Write-Output "$exeName -> $mitiName"
        } else {
            foreach ($attrName in $trueAttrs) {
                Write-Output "$exeName -> $mitiName $attrName"
            }
        }
    }
}

运行后输出结果和你期望的格式完全一致。

方案2:处理已转换完成的JSON文件

如果已经完成XML转JSON,可使用以下PowerShell脚本遍历提取符合要求的路径:

# 读取JSON文件
$jsonContent = Get-Content -Path "转换后的文件路径.json" -Raw | ConvertFrom-Json

# 递归遍历JSON节点查找值为true的项
function Get-TruePath {
    param (
        $Node,
        [string]$ParentPath = ""
    )
    if ($Node -is [PSCustomObject]) {
        foreach ($prop in $Node.PSObject.Properties) {
            if ($prop.Name -eq 'Executable') {
                $script:currentExe = $prop.Value
                continue
            }
            $newPath = if ($ParentPath) { "$ParentPath $($prop.Name)" } else { $prop.Name }
            if ($prop.Value -eq 'true') {
                Write-Output "$currentExe -> $newPath"
            } else {
                Get-TruePath -Node $prop.Value -ParentPath $newPath
            }
        }
    }
}

foreach ($appItem in $jsonContent) {
    Get-TruePath -Node $appItem
}

内容的提问来源于stack exchange,提问作者paal527569

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 00:54:04