Parsing an XML File Using PowerShell

One of my applications generates an XML file below.

<root> <command name="Set"> <property name="PWR.WakeupOnLAN" value="6" errorcode="0x0"/> </command> <command name="Set"> </command> <command name="biossettings"> <property name="task" value="Succeeded." errorcode="0x0"/> </command> </root> 

I am interested in reading the values ​​and error codes of the property name PWR.WakeupOnLAN. Before publishing here, I tried different things, but could not find the correct code for reading properties in powershell. Can someone help me with powershell code for this?

+7
source share
3 answers

In PowerShell 2.0, you can solve this problem using the new Select-Xml cmdlet and XPath :

 [xml]$document = "<root><command name='Set'><property name='PWR.WakeupOnLAN' value='6' errorcode='0x0'/></command><command name='Set'></command><command name='biossettings'><property name='task' value='Succeeded.' errorcode='0x0'/></command>" $value = (Select-Xml -Xpath "//property[@name='PWR.WakeupOnLAN']/@value" $document).Node.Value $errorCode = (Select-Xml -Xpath "//property[@name='PWR.WakeupOnLAN']/@errorcode" $document).Node.Value 

Related Resources:

+12
source

@Enrico Campidoglio gives the β€œcleanest” solution, it’s a kind of old fashion.

 PS> $xml = [XML](get-content c:\temp\yourfile.xml) PS> $errcode = ($xml.root.command | where {$_.property.name -eq "PWR.WakeupOnLAN" }).property.errorcode 
+8
source

Another possibility is to create a function. Similar to JPBlanc solution.

 function Get-Info ($name='PWR.WakeupOnLAN', $targetXml){ $properties = $targetXml.GetElementsByTagName("property") $properties | Where {$_.Name -eq $name} } Get-Info -targetXml $xml Get-Info -name Task -targetXml $xml 
+2
source

All Articles