xmlpowershellregexp-replace

Powershell script to mask the passwords in config file


I have a config text file that contains several passwords. I wrote a PowerShell script to replace the passwords with xxxxxxxxxxxxxxxxxxxxxxxxxxx. But it does not seem to be doing anything. Can someone please explain to me what I did wrong? The regex expression works when I use it in notepad++.

TIA

(Get-Content test-config.xml) `
    -replace '"(?-s)<bind-password>(.*?)<//bind-password>"', '<bind-password>xxxxxxxxxxxxxxxxxxxxxxxxxxx</bind-password>' `
    -replace '"(?-s)<secret>(.*?)<//secret>"', '<secret>xxxxxxxxxxxxxxxxxxxxxxxxxxx</secret>' |
  Out-File test-config-cleaned.xml

a sample config would have this

            <entry name="radius-1">
              <secret>12324zxzczxczxcasd</secret>
              <port>1812</port>
              <ip-address>192.168.100.100</ip-address>
            </entry>

          <bind-password>231231sdfsdfsdfsccc</bind-password>

The output file should have been like this

            <entry name="radius-1">
              <secret>xxxxxxxxxxxxxxxxxxxxxxxxxxx</secret>
              <port>1812</port>
              <ip-address>192.168.100.100</ip-address>
            </entry>

          <bind-password>xxxxxxxxxxxxxxxxxxxxxxxxxxx</bind-password>

Solution

  • Use XmlDocument instead of regex:

    $path = Convert-Path .\test-config.xml
    $xml = [xml]::new()
    $xml.Load($path)
    $xml.GetElementsByTagName('secret') | ForEach-Object {
        $_.InnerText = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
    }
    $xml.GetElementsByTagName('bind-password') | ForEach-Object {
        $_.InnerText = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
    }
    
    $xml.Save('path\to\test-config-cleaned.xml')