Read XML-file in PowerShell

Today I will show you how to read a XML-file, something with endless possibilities. An example is if you have a file that contains information about users and you need to create new accounts in the Active Directory.

First, let us take a look of an example file that I’ve created that contains information about two persons, John Doe and Jane Doe.

<?xml version="1.0" encoding="ISO-8859-1"?>
		<formattedName>Doe John</formattedName>
			<workSiteId>New York</workSiteId>
		<formattedName>Doe Jane</formattedName>
			<workSiteId>New York</workSiteId>

As you can see in the example above, each user is stored under <Person></Person> with one extra section for “Telephone” and “Employment”.

To get the information from the file, the first step is to import the file and get the content. This is done with the following two lines:

$XMLfile = 'D:\XML\TestUser.xml'
[XML]$xml = Get-Content $XMLfile

Now, if you type $xml in the console you will see that the output is only the first element in the XML-file, in this case “?xml version=”1.0″ encoding=”ISO-8859-1″?”.
But to the right, you will see the first subsection of the file, “HR”.


If we want to see what is under “HR” we simply type “$xml.HR”. The result of this shows that there are two subsections called “Person”.


To see the content of each “Person” we type, as you’ve probably guessed, “$xml.HR.Person” and are presented with:


This is the very basics of reading a XML-file with PowerShell. It’s quite easy once you understand how the file is built and what needs be accessed.

In the last example you can see that the information “Telephone” and “Employment” isn’t listed with the values of the file. To get this, we need to access the one specific person.
The easiest way to do this is with a “ForEach-loop”. The sample script bellow will write theĀ formatted name with the users phone-numbers bellow:

foreach($person in $xml.HR.Person){
    Write-Host $person.formattedName
    Write-Host $person.Telephone.businessNumber
    Write-Host $person.Telephone.mobileNumber
    Write-Host ''

The result will be:


In the next part I will show you how to write to a XML-file from PowerShell.
This part can be found HERE when released!

This entry was posted in Powershell and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *