, ,

Powershell: Parsing XML part 1

1–2 minutes
4 comments on Powershell: Parsing XML part 1
PowerShell

In my company, we started to use XML files as configuration files. So we use it for some configurations of servers or automation for our robots. In Powershell, there is a pretty easy way for parsing XML. In Powershell there is an object type for XML, so you just can use the get-content Cmdlet to read the XML file into the object.

$xmldata = get-content "C:\XMLFiles\mydata.xml"

When you create a function for reading XML files you also can set the XML object to global.

$global:xmldata = get-content "C:\XMLFiles\mydata.xml"

Now $xmldata is an object which includes all the data of the mydata.xml.

Let’s view the content of the mydata.xml file. We need this to understand the following commands.

 
 
Peter 
Administration 
[email protected] 
 
 
Thomas 
Administration 
[email protected] 
 
 
Steve 
IT 
[email protected] 
 

Now we wanna get all unique Accounts listed

$xmldata.TodoList.Task | %{$_.Name} | select-object -unique
Peter
Thomas
Stefan

We can also create a new object for a specific Task

[Object]$xmltask2 = $xmldata.TodoList.Task | Where-Object {$_.ID -eq "2"}

Now we have a new object with data from Task ID 2. If we wanna see the name from this we just use the same command with the new object

$xmltask3 | {$_.Name}
Thomas

We can do a lot more with this, but I will bring this up in the next blog posts.

4 responses

  1. eric Avatar

    Using your post as a guide. Trying to parse an xml file on a website and save the results of one of the fields to a text file. When I do an invoke-webrequest I get nothing.

  2. bkwdesign Avatar

    Would like to see you delete an object from the array and re-save the XML file

  3. john Avatar

    It seems that you jumped ahead without explaining what you were doing. how do I pull the item out of the xml file?

  4. Manuel Avatar

    Hi John,
    If I understand your question… here is the answer:
    At the top of this article is the command:

    $xmldata = get-content “C:\XMLFiles\mydata.xml”

    This places the contents of the mydata.xml file… which is located in the “C:\XMLFiles” directory.

    Please excuse, if I misunderstood.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.