Handling XML with PowerShell is very simple. It converts XML elements to properties on .NET objects without the need to write any parsing code. So it is very easy to use XML with PowerShell. Here we are going to discuss how to read the XML file values in different ways.

You can also read  How to add values to the string array from xml using Powershell and  How to write data to an xml file using Powershell 

A Quick Example

XML File : MyXM.xml

Method 1:

Once you’ve run Get-Content to read the raw text from the XML document and cast the output to type [XML], you now have a variable called $XmlDocument that contains the entire XML node tree which we can process.

STEP  #1: Assign the XML file location into the variable.

$XMLfile = ‘C:\donet-helpers\Demo\MyXM.xml’

STEP  #2: Read the xml file using get-content cmdlet and assign to variable. The [xml] casts the variable as an XML object.

[XML]$empDetails = Get-Content $XMLfile

STEP  #3: Looping the child node to get the value.

foreach($empDetail in $empDetails.EmpDetails.Person){ }

Final Code:

OUTPUT:

Method 2:

STEP  #1: Assign the XML file location into the variable.

$Path = “C:\donet-helpers\Demo\MyXM.xml”

STEP  #2: The below command saves the XML path to the AliasProperty node in the $XPath variable.

$XPath = “/EmpDetails/Person”

STEP  #3: The Select-Xml cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.

Select-Xml -Path $Path -XPath $Xpath | Select-Object -ExpandProperty Node

Final Code:

 

What do you think?

I hope you have an idea of how to Reading XML Files With PowerShell. I would like to have feedback from the readers of my posts. Your valuable feedback, question, or comments about this article are always welcome.