Powershell Read XML File Example Tutorial

I was going through the features of Powershell today and was fascinated by the XML handling capabilities of  the tool. In this tutorial, I'm going to provide a very basic example of reading an XML document stored in the hard disk into Powershell and print the content to the console. Once we are done reading an XML document, I will explain how to query an XML document for the content we are looking after, and print the output to the console. This will be very useful for administrators who want find a way to  manipulate XML documents using this tool.  This simple tip is classified into the following sections:

Prepare Input XML for PowerShell

The XML file we will be using for this example is provided below: [ Note that we will be using the same file across all the tutorials ]
<?xml version="1.0" encoding="UTF-8"?>

I have saved this document under my c: with the name read_xml_example.xml.

Use PowerShell to Read XML Document

We now use PowerShell to access the XML file we just created. This is done using the command shown below:
PS C:\> [xml]$departments=Get-Content c:\read_xml_example.xml

We use Get-Content to load the data in the file to the variable departments.

Test XML Data in PowerShell

You can print the contents of the file we loaded just now to check if the loading is successful. To print the nodes of the XML you can execute the following command;
PS C:\> $departments.departments.item

This command dumps all the item nodes with contents as shown below:
PS C:\> $departments.departments.item

deptid                     deptname                   employeecount
------                     --------                   -------------
100                        marketing                  100
101                        finance                    75
102                        HR                         15
103                        IT                         250
104                        Operations                 50

Wow! you have loaded XML data successfully in Powershell. That completes the first powershell XML example. If you try to print the "departments" node, you get an exception as shown below:

PS C:\> $departments.departments
format-default : The member "Item" is already present.
    + CategoryInfo          : NotSpecified: (:) [format-default], ExtendedType
    + FullyQualifiedErrorId : AlreadyPresentPSMemberInfoInternalCollectionAdd,

The error message here is self explanatory. There are different techniques available in Powershell to query the XML that we just loaded. We will look into each of these parsing techniques in the next tutorial.

No comments:

Post a Comment