Welcome to ciysys blog

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

Jump to #POWERSHELL blog

Author

Lau Hon Wan, software developer.