We already discussed the reading/Writing XML file using PowerShell in previous posts and How to add values to the string array from XML using Powershell. Now in this post, we will discuss How to add values to the Objects With [pscustomobject] from XML using Powershell. 

PowerShell has XPath but you don’t have necessarily have to use it. Instead of XPath, PowerShell provides the simplest/Easiest way to read XML files, manipulate the XML document, we use the same in the example below. For this demo, we have created a PCdetails.xml file as shown below.

PCdetails.xml File

STEP 1:

The simplest way to read an XML document in PowerShell is to typecast a variable to the type [XML]. To create this variable, you can use the Get-Content cmdlet to read all of the text in an XML document. To typecast the output of Get-Content we can simply prepend the text [xml] before the variable. This tells PowerShell that we need this variable typecasted as a System.Xml.XmlDocument type instead of the default array type that normally comes from Get-Content.

$XML1Filepath = “C:\dotnet-helper\PCdetails.xml”

Once you’ve executed the above cmdlet, the Get-Content cmdlet will read all the raw text from the XML document and cast the output to type System.Xml.XmlDocument, you now have a variable called $XmlDocument that contains the entire XML node tree that represents that document.

STEP 2:

After the execution of STEP 1, the $XmlDocument variable will have the entire XML node tree. Now you can loop the XML element from the parent Node. Here I am fetching all the child elements present under the SYSTEM_INFORMATION element.

$PCVersionsDetails = $XmlDocument.GET_DATA.SYSTEM_INFORMATION.ChildNodes | ForEach-Object {
[pscustomobject]@{
Name = $_.PART_NAME.Value;
Version = $_.PART_VERSION.Value
}
}

STEP 3:

Finally print the Object data.

$PCVersionsDetails

Final Code:

OUTPUT: