7

One of my application is generating below XML file.

<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 value and errorcodes of "PWR.WakeupOnLAN" property name. Before posting here, I tried various things but couldn't find correct code for reading properties in powershell. Can any one help me with powershell code for this?

1
  • Please mark the correction answer. Commented May 10, 2011 at 6:44

3 Answers 3

12

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

[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:

Sign up to request clarification or add additional context in comments.

Comments

8

@Enrico Campidoglio gives the "cleanest" solution here is 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

1 Comment

+1 for backwards compatibility. Your example will work in both PowerShell 1.0 and 2.0.
2

Another possibility, is to create a function. Similar to JPBlanc's 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

1 Comment

@all Thanks for the answers. These really helped me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.