Working with XML in PowerShell

PowerShell variables are very accommodating creatures. You can assign any value to them and the variable will automatically store it in an appropriate data type. This is great 99% of the time – you can throw the result of any sort of cmdlet at them and leave PowerShell to sort itself out. Having assigned the value to the variable, PowerShell ISE’s intellisense will let you know the properties and methods you can access in the variable’s new state.

For the record, this is called ‘loose’ or ‘weak’ typing. You’ll find a similar approach in other languages, JavaScript or PHP, for example.

One time you might want to consider specifying the type of a variable in PowerShell is when working with xml. Take the following xml:

<root>
    <header>
        <order_no>12345</order_no>
        <line>
            <item_no>ABC</item_no>
            <quantity>2</quantity>
        </line>
        <line>
            <item_no>XYZ</item_no>
            <quantity>5</quantity>           
        </line>
    </header>
</root>

If I load the content of a file containing that xml into a variable with Get-Content, PowerShell will type the variable as a string and give me stringy properties and methods.

String Example

If I declare $OrderXml to be of type [xml], however, I get a different set of properties and methods. Far more useful for selecting nodes, iterating through NodeLists and other essential XML stuff.

Xml Example

The $Line variable even has properties for each of its child nodes, allowing you to access their values directly. This is the corresponding output:

PS C:\WINDOWS\system32> [xml]$OrderXml = Get-Content "C:\Users\James.Pearson\Desktop\test.xml"
foreach ($Line in $OrderXml.SelectNodes('/root/header/line'))
{
    $Line.item_no
    $Line.quantity
}
ABC
2
XYZ
5

Leave a Reply