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"> <name>Peter</name> <dept>Administration</dept> <email>[email protected]</email> </task> <task action="create" ID="2"> <name>Thomas</name> <dept>Administration</dept> <email>[email protected]</email> </task> <task action="delete" ID="3"> <name>Steve</name> <dept>IT</dept> <email>[email protected]</email> </task>
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.
Tags: commands, get-content, Microsoft, Microsoft Powershell, objects, parsing XML, parsing XML with Powershell, PowerShell, Powershell Commands, PowerShell XML, read XML, Windows, XML Last modified: February 2, 2020
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.
Would like to see you delete an object from the array and re-save the XML file
It seems that you jumped ahead without explaining what you were doing. how do I pull the item out of the xml file?
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.