Using XML in your PowerShell scripting

I have written a lot of scripts that use .txt files to read or store data, but I have a need to read some information from an .xml file.  This could be done by treating the file as a simple txt file, but it would require some pretty good filtering that is already a part of the xml file.  A quick search helped me locate this article:

http://blogs.msdn.com/kalleb/archive/2008/07/19/using-powershell-to-read-xml-files.aspx

Which contained the key to helping me with what I needed to do.  The specific piece I needed was in Lesson 2:

Lesson 2:
Read data from an XML-file.
The XML-file that I’m going to read from has the following structure:
<Users>
  <User>
    <Name>Kalle</Name>
</User>
  <User>
    <Name>Becker</Name>
  </User>
</Users>
Reading data from an XML-file is really easy in PowerShell! Use this command to load the file into an variable:
PS C:\Tmp> [xml]$userfile = Get-Content Accounts.xml

When the xml-file is loaded you can type “$userfile.U” and press tab to get auto completion!! It’s a breeze.

The trick is that you have to actually READ what is in front of you.  The key here is to let PowerShell know that you are reading an xml file, and that is done by placing [xml] prior to getting the content.  I missed that the first six times I read this and couldn’t figure out why I wasn’t getting the results I expected.

Leave a Reply