Modify config files using PowerShell

Suppose you need to hide the password in your clear text connection strings at a particular back-up path or any other path in config files. This can be achieved using PowerShell with the following code.

$configFiles = Get-ChildItem "C:\Path\Backup" *.config -rec
foreach ($file in $configFiles)
{
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace "pwd=(\w+);", "pwd=****;" } |
    Set-Content $file.PSPath
}

Write-Verbose "Password changed!"

The above script will replace the string “pwd=(\w+);” with “pwd=****;” in the *.config files matching the regular expression.

I’m using the following parameters for the Get-ChildItem command:

-Path “C:\Path\Backup” 

-Include *.config for including config files

-rec for Recursion to get items in all child containers