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

PowerShell:如何用NamespaceManager定位gpresult XML中的指定GPO节点

问题:通过GPO名称在gpresult生成的XML中查找对应Policy节点的State

我现在尝试通过GPO名称,使用SelectSingleNode在gpresult生成的XML文档中查找特定GPO,但XML节点带有q24:Name这类命名空间,因此遇到了困难。

XML结构示例

<Rsop xmlns:xsd="URL" xmlns:xsi="URL" xmlns="http://www.microsoft.com/GroupPolicy/Rsop">
<ReadTime>2024-03-20T13:45:23.8888739Z</ReadTime>
<DataType>LoggedData</DataType>
<UserResults>
...
</UserResults>
<ComputerResults>
...
<q24:Policy>
<GPO xmlns="URL">
<Identifier xmlns="http://www.microsoft.com/GroupPolicy/Types">{FC2D09DB-6814-4939-8971-8B459C5E9977}</Identifier>
<Domain xmlns="URL">officelan.izb</Domain>
</GPO>
<Precedence xmlns="URL">1</Precedence>
<q24:Name>Configure Drive Maps preference logging and tracing</q24:Name>
<q24:State>Enabled</q24:State>  
</q24:Policy>
</ComputerResults>
</Rsop>

我希望通过名称找到Policy节点并返回其State。以下是我编写的代码:

编写的PowerShell代码

function Check-GPO {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string]$XmlPath,
        [Parameter(Mandatory=$true)]
        [string]$policyName,
        [string[]]$Namespaces = @("q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15", "q16", "q17", "q18", "q19", "q24")
    )

[xml]$xmlData = cat $xmlPath

$policyU = $xmlData.Rsop.UserResults.GPO | Where-Object { $_.Name -eq $policyName }
#$policyPC = $xmlData.Rsop.ComputerResults.ExtensionData.Extension.Policy.GPO | Where-Object { $_.Name -eq $policyName }

#namespacemanager
$nsManager = New-Object System.Xml.XmlNamespaceManager($xmlData.NameTable)


foreach ($ns in $Namespaces) {
        $nsManager.AddNamespace($ns, "URL")
    }

$xpath = "//q24:Name[text()='$policyName']"#"//Policy[Name='$policyName']"
$policyPC = $xmlData.SelectSingleNode($xpath, $nsManager)
    
if ($policyU -or $policyPC) {
    if ($policyU.Link.Enabled -eq "true") {
    Write-Output "Die User-Gruppenrichtlinie '$policyName' ist aktiviert."
    } 
    elseif($policyPC.State -eq "Enabled") {
    Write-output "Die PC-Gruppenrichtlinie '$policyName' ist aktiviert."
    }
    else { Write-Output "Die Gruppenrichtlinie ist deaktiviert." }
}

else {
    Write-Output "Die Gruppenrichtlinie '$policyName' existiert nicht."
}
}

感谢您的任何反馈。

附言:由于Stackoverflow反垃圾机制,我已将所有真实URL替换为"URL"。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 18:44:56