Handling XML in Powershell
Published on: 4th May 2020
Updated on: 16th Jan 2022
Explanation
In Powershell, it is very easy in handling XML data structure as compared to C#. This is because Powershell is not statically typed and the property access can be determined at runtime.
The following example shows how to change the value in an AppSetting node in an ASP.NET web.config file:
$f = "$PSScriptRoot\web.config"
# read xml file - the most important is type casting the variable with "[xml]".
[xml]$xml = Get-Content $f
# show the nodes in "appSettings"
$xml.configuration.appSettings.add | Format-Table -AutoSize
# changing the appSetting
$xml.configuration.appSettings.add[1].value = "1"
# save changes to file
$xml.Save($f)
Use case
- When deploying an ASP.NET application to a customer site, you may automate the changes (to the web.config). As a result, there were fewer mistakes in the deployment.
Jump to #POWERSHELL blog
Author
Lau Hon Wan, software developer.