尝试从xml文件中选择单个节点失败

问题描述 投票:1回答:1

在PowerShell脚本中,我尝试从此XML文件中选择第二个MemberShipRule(对于UnixComponentGroup):

<Discoveries>
  <Discovery ID="Service_ARCHIBUS_SCPopulation" Enabled="true" Target="Service_ARCHIBUS" ConfirmDelivery="false" Remotable="true" Priority="Normal">
    <Category>Discovery</Category>
    <DiscoveryTypes />
    <DataSource ID="DS" TypeID="SystemCenter!Microsoft.SystemCenter.GroupPopulator">
      <RuleId>$MPElement$</RuleId>
      <GroupInstanceId>$Target/Id$</GroupInstanceId>
      <MembershipRules>
        <MembershipRule>
          <MonitoringClass>$MPElement[Name="WindowsComponentGroup_Service_ARCHIBUS"]$</MonitoringClass>
          <RelationshipClass>$MPElement[Name="ATS.Application.ARCHIBUS.WindowsServiceHealthRollup"]$</RelationshipClass>
        </MembershipRule>
        <MembershipRule>
          <MonitoringClass>$MPElement[Name="UnixComponentGroup_Service_ARCHIBUS"]$</MonitoringClass>
          <RelationshipClass>$MPElement[Name="ATS.Application.ARCHIBUS.UnixServiceHealthRollup"]$</RelationshipClass>
        </MembershipRule>
      </MembershipRules>
    </DataSource>
  </Discovery>
 </Discoveries>

字符串“ARCHIBUS”存储在变量$ appnorm中。我尝试了不同的版本,我的最后一个是:

$xml = Get-Content $apppath
$appnorm = "ARCHIBUS"
$node = $xml.SelectSingleNode('//MembershipRule/MonitoringClass[.=$MPElement[Name="UnixComponentGroup_Service_' + $appnorm + '"]$]')

结果总是null值。如果有人可以帮助我会很棒。

谢谢!

亲切的问候

乌尔夫

xml powershell selectsinglenode
1个回答
1
投票

那是因为你的$xml对象是一个字符串。因为它没有那个方法(您可以将任何对象传递给Get-Member以查看其类型和方法)。因此,您需要首先将其强制转换为xml,然后您可以在其上调用SelectSingleNode,但我会使用简化的PowerShell语法搜索您的元素:

[xml]$xml = Get-Content $apppath
$appnorm = "ARCHIBUS"
$xml.Discoveries.Discovery.DataSource.MembershipRules.MembershipRule | Where-Object { $_.MonitoringClass -eq "`$MPElement[Name=`"WindowsComponentGroup_Service_$appnorm`"]`$" }
© www.soinside.com 2019 - 2024. All rights reserved.