Search code examples
xmlpowershelliispowershell-isepowershell-cmdlet

How to remove particular tag from XML file using Powershell?


From below xml snippet I want to remove only "ConnectionString" tag from <appSettings> parent tag:

     <configuration>  
        <appSettings>
            <add key="ConnectionString" value=" Data Source=192.168.1.19;Network Library=DBMSSOCN;Initial Catalog=Demo;Persist Security Info=True; User ID=sa;Password=powershell;Application Name=web;Connect Timeout=200; pooling='true'; Max Pool Size=200;"/>
            <add key="ConnectionString1" value=" Data Source=192.168.1.19;Network Library=DBMSSOCN;Initial Catalog=Demo;Persist Security Info=True; User ID=sa;Password=powershell;Application Name=web;Connect Timeout=200; pooling='true'; Max Pool Size=200;"/>
            <add key="ConnectionString2" value=" Data Source=192.168.1.19;Network Library=DBMSSOCN;Initial Catalog=Demo;Persist Security Info=True; User ID=sa;Password=powershell;Application Name=web;Connect Timeout=200; pooling='true'; Max Pool Size=200;"/>
          </appSettings>
    </configuration>

Please let me know how to do this using powershell?


Solution

  • Try this:

    # Set file path
    $File = '.\config.xml'
    
    # Get file contents as XML
    [xml]$xml = Get-Content $File
    
    # Find node with key="ConnectionString"
    $Remove = $xml.appSettings.configuration.appSettings.add |
                    Where-Object {$_.Key -eq 'ConnectionString'}
    
    # Remove this node from it's parent
    $xml.appSettings.configuration.appSettings.RemoveChild($Remove) | Out-Null
    
    # Save file
    $xml.Save($File)