Small Tips and Tricks – PowerShell – how to read content from XML file

Hi All,
Greetings for the day!!!
Today new learning for me so sharing 🙂
In this article we will discuss how to read XML file in PowerShell script
Background
- In one of the PowerShell script we have an requirement of reading XML file
- Even though very common requirement but new for me – reading XML file in PowerShell
- We have very good articles on reading CSV and Text files
- Small Tips and Tricks – PowerShell – how to read content from text file – https://knowledge-junction.in/2023/02/10/small-tips-and-tricks-powershell-how-to-read-content-from-text-file/
- Read a CSV file with PowerShell using the Import-CSV function – https://knowledge-junction.in/2022/10/29/read-a-csv-file-with-powershell-using-the-import-csv-function/
Details
- Its very similar how we read text file with PowerShell
- We will use Get-Content CMDLET is used to read the XML file from given path
- Get-Content CMDLET reads file line by line
- Consider following XML file – Here I am explicitly taking .NET configuration file – App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ScriptPath" value="C:\\knoweldgejunction_powershell.ps1"/>
<add key="UserName" value="knowledgejunction"/>
<add key="Password" value="lifeisbeautiful"/>
</appSettings>
</configuration>
- So lets consider we need to read the username and password from above XML file – App.config
- We will use Get-Content CMDLET as
[XML]$creds = Get-Content -Path "App.config"
- Make sure we are type-casting output variable ($creds) with [XML]
- Output of the above CMDLET is
xml configuration
--- -------------
version="1.0" encoding="utf-8" configuration
- We get very first node (top node) – <configuration>
- As we have top node, we can loop through the child nodes or we can read individual nodes as well
- Example –
$creds.configuration
o/p -
appSettings
-----------
appSettings
- Now here to read user name and password – we need to loop though all the keys under <appSettings> and get the respective values as
foreach($key in $creds.configuration.appSettings.add)
{
if($key.key -eq "UserName"){
$username = $key.value
}#if
if($key.key -eq "Password"){
$password = $key.value
}#if
}#foreach
Complete Script
$username=""
$password=""
[XML]$creds = Get-Content -Path "App.config"
foreach($key in $creds.configuration.appSettings.add)
{
if($key.key -eq "UserName"){
$username = $key.value
}#if
if($key.key -eq "Password"){
$password = $key.value
}#if
}#foreach
Write-Host "UserName is" $username
Write-Host "Password is" $password
Thanks for reading 🙂 HAVE a FANTASTIC TIME AHEAD 🙂
You must log in to post a comment.