Using PowerShell to Manipulate XML files

I was recently asked to manipulate a .NET machine.config file from PowerShell.

As a .NET developer in the 21st century I hoped to use System.Xml.Linq. However, I was left banging my head on the desk after trying to use extension methods - and getting lambda expressions to work was simply a bridge to far...

So instead I fell back to System.Xml - which is still perfectly usable and requires a lot less voodoo to get working:

# NB - you need to target the machine config according to the bit-ness of the application
# either 32 bit: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config
# or 64 bit: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config
 
$fileName = “C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config”
$xmlDoc = [System.Xml.XmlDocument](Get-Content $fileName)
 
$existingElement = $xmlDoc.SelectSingleNode("//configuration/appSettings/add[@key = 'ARCS2G.DBConfigFilePath']")
 
if ($existingElement -eq $null)
{
    $appSettingsElement = $xmlDoc.SelectSingleNode("//configuration/appSettings")
    
    if ($appSettingsElement -eq $null)
    {
        $appSettingsElement = $xmlDoc.configuration.AppendChild($xmlDoc.CreateElement("appSettings"))
    }
    
    # not sure whether clear is desirable in machine.config - could affect other .NET apps...
    $clearElement = $xmlDoc.SelectSingleNode("//configuration/appSettings/clear")
    
    if ($clearElement -eq $null)
    {
        $clearElement = $appSettingsElement.AppendChild($xmlDoc.CreateElement("clear"))
    }
    
    $addElement = $xmlDoc.SelectSingleNode("//configuration/appSettings/add[@key = 'ARCS2G.DBConfigFilePath']")
    
    if ($addElement -eq $null)
    {     
        $addElement = $appSettingsElement.AppendChild($xmlDoc.CreateElement("add"))
        $addElement.SetAttribute("key","ARCS2G.DBConfigFilePath")
        $addElement.SetAttribute("value","\\server\ARCS2G\Config")
    }
     
    $xmlDoc.Save($fileName)
}

Comments