PowerShell从具有多个属性的XML中获取属性值
以下XML文件是从带PowerShell 2的2008 R2故障转移群集运行的Get ClusterGroup命令输出的一个对象节点:PowerShell从具有多个属性的XML中获取属性值,xml,powershell,siblings,Xml,Powershell,Siblings,以下XML文件是从带PowerShell 2的2008 R2故障转移群集运行的Get ClusterGroup命令输出的一个对象节点: <?xml version="1.0"?> <Objects> <Object> <Property Name="Cluster">Cluster1</Property> <Property Name="IsCoreGroup">False</Property>
<?xml version="1.0"?>
<Objects>
<Object>
<Property Name="Cluster">Cluster1</Property>
<Property Name="IsCoreGroup">False</Property>
<Property Name="OwnerNode">Node1</Property>
<Property Name="State">Offline</Property>
<Property Name="Name">SAP PL1</Property>
<Property Name="Description" />
<Property Name="PersistentState">1</Property>
<Property Name="FailoverThreshold">4294967295</Property>
<Property Name="FailoverPeriod">6</Property>
<Property Name="AutoFailbackType">1</Property>
<Property Name="FailbackWindowStart">4294967295</Property>
<Property Name="FailbackWindowEnd">4294967295</Property>
<Property Name="Priority">1</Property>
<Property Name="DefaultOwner">4294967295</Property>
<Property Name="AntiAffinityClassNames" />
<Property Name="Id">a5ff557f-c81a-43aa-bdb9-e09d0a1103df</Property>
</Object>
</Objects>
这给了我以下信息:
Name #text
---- -----
IsCoreGroup False
但我不知道如何获得兄弟属性
我尝试用以下方法备份一个级别:
[xml]$file = get-content C:\Admin\ClusterGroups.xml
$xmlObjects = $file.SelectNodes("/Objects/Object")
Foreach ($xmlObject in $xmlObjects) {
$strCoreGroup = ($xmlObject | Where-Object {$_.Property.Name -eq "IsCoreGroup" }).InnerXml
If ($strCoreGroup -eq "False")
{
Echo $xmlObject
}
}
但这对我没有任何帮助
非常感谢您的帮助 如果您是属性元素上的变量点,则需要访问parentnode。因为您需要找到一个属性元素,其中名称是属性值,所以我更喜欢使用xpath来实现这一点
$xmlProperties = $file.SelectNodes("/Objects/Object/Property")
Foreach ($xmlProperty in $xmlProperties) {
$strName = ($xmlProperty | Where-Object {$_.Name -eq "IsCoreGroup" }).InnerXml
If ($strName -eq "False")
{
# .. means parent node. So the xpath goes up one level from property, and searches for the new property you want.
$xmlProperty.SelectSingleNode('../Property[@Name="Name"]').InnerXml
}
}
您还可以执行$xmlproperty.parentnode.whateveryouwant
就我个人而言,我会使用xpath来搜索正确的对象,并在对象级别检索它们,这样您就可以轻松地访问对象节点中的其他属性,而无需升级
$file.SelectNodes('/Objects/Object[Property[@Name="IsCoreGroup"]="False"]') | % {
#Foreach object with IsCoreGroup = false, get value of property with Cluster1 as Name attribute
$_.SelectSingleNode('Property[@Name="Cluster"]').innerxml
}
Cluster1
太好了!非常感谢。唯一的缺点是XPath查询是区分大小写的,所以如果有两个文档的大小写不一致,XPath查询将在一个文档中工作,而在另一个文档中失败。这是事实。但对于计算机生成的文件,情况通常是静态的(至少当文件是新的,而不仅仅是更新的时是如此)
$file.SelectNodes('/Objects/Object[Property[@Name="IsCoreGroup"]="False"]') | % {
#Foreach object with IsCoreGroup = false, get value of property with Cluster1 as Name attribute
$_.SelectSingleNode('Property[@Name="Cluster"]').innerxml
}
Cluster1