Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

            <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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading