Written by 4:51 pm Microsoft, PowerShell, Windows • 4 Comments

Powershell: Parsing XML part 1


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.

<TodoList ID = "Week21"> 
<task action="create" ID="1"> 
<email>[email protected]</email> 
<task action="create" ID="2"> 
<email>[email protected]</email> 
<task action="delete" ID="3"> 
<email>[email protected]</email> 

Now we wanna get all unique Accounts listed

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

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}

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

Tags: , , , , , , , , , , , , Last modified: February 2, 2020
Close Search Window