【发布时间】:2022-11-10 03:36:26
【问题描述】:
您好亲爱的 Powershell 专家,
我需要一些建议。我尝试使用 Powershell 变量(我从参数中获取)来处理 XML 路径/节点。
我的情景
下面的代码显示了我的代码的简短剪辑。有了这个切口,我将尝试尽可能详细地解释我的问题。
foreach ($Gpo in $AllGpos) {
[xml]$selected_Gpo = Get-GPOReport -ReportType Xml -Guid $Gpo.Id
$policy_object = $selected_Gpo.GPO.Computer.ExtensionData.Extension
if ($policy_object.$Policy_Identity_XMLPath_Name -eq $Policy_Identity_Name) {
if ($policy_object.$Setting_XMLPath_Name -eq $Policy_Identity_Setting_Name -and $policy_object.$Setting_XMLPath_Value -eq $Policy_Identity_Setting_Value) {
}
...
我遍历所有组策略对象(在 Active Directory 环境中),生成 GPO 的 xml 报告,然后在此 xml 文件中搜索特定的组策略设置。只要我使用硬编码的 xml 节点路径,这种方法就可以很好地工作。例如: 而不是使用“$policy_object.$Policy_Identity_XMLPath_Name -eq $Policy_Identity_Name”,我可以使用“$policy_object.Policy.DropDownList.Name -eq”示例设置。但我无法使用这些硬编码的 xml 节点路径并想使用变量来在 xml 文件中处理这些路径。
示例 XML 的快捷方式
<q1:Policy>
<q1:Name>TestName</q1:Name>
<q1:State>Enabled</q1:State>
<q1:Explain>Test Explaination </q1:Explain>
<q1:Supported>Testsupported version</q1:Supported>
<q1:Category>Test Category</q1:Category>
<q1:DropDownList>
<q1:Name>Test Name DropDownList</q1:Name>
<q1:State>Enabled</q1:State>
<q1:Value>
<q1:Name>TestName Value</q1:Name>
</q1:Value>
</q1:DropDownList>
</q1:Policy>
我的问题
问题是,我无法使用 powershell 变量解决 xml 路径。当我使用上面代码示例中的变量 ($policy_object.$Policy_Identity_XMLPath_Name) 时,我会返回 null,因此我的 if 语句不再起作用。
到目前为止我做了什么
当然,我做了很多试验和错误的事情,用变量来获取 powershell 地址这些 xml 节点路径。我试图将 ($policy_object.$Policy_Identity_XMLPath_Name) 放在不同类型的引号中。 我也已经看到堆栈溢出帖子有一个非常相似的问题 (Parsing an XML file with PowerShell with node from variable) 但是这些解决方案基本上还不错,但在我的具体场景中没有用。 让我解释:
$Policy_Identity_Setting_XMLPath_Name = 'GPO/Computer/ExtensionData/Extension/SecurityOptions/Display/DisplayFields/Field/Name'
$test = policy_object.SelectNodes($Policy_Identity_Setting_XMLPath_Name)
=> 结果为空。不知道为什么说实话
$ExecutionContext.InvokeCommand.ExpandString("`$(`policy_object.$Policy_Identity_Setting_XMLPath_Name)")
这将导致“可接受的”结果。但在我的场景中,结果主要是多个值(GPO 设置),并将它们全部存储在一个巨大的字符串中。之后我无法访问此字符串中的特定值。所以这种方法也不理想,因为我无法进一步处理结果。
希望各位小伙伴有好的想法。也许我在我的大脑逻辑中让它变得比必要的更复杂。 如果您需要更多信息,请告诉我。
【问题讨论】:
标签: xml powershell parsing variables gpo