![Search and Replace in Powershell](/img/thumbnails/parcel-420x255.webp)
Search and Replace in Powershell
In scenarios where we keep configuration information in app.config or web.config files (or .cscfg's even), there is often a need to replace non-secret dev settings for local machines with settings referencing protected resources, for example, production database credentials.
This little script is aimed at a quick and dirty solution to that problem, replacing the placeholder keys in the hash with the "production" values. Of course, for a production system the actual settings could be imported from a file as a command line param rather than being hard-coded.
Function Replace-ConfigSecrets {
[CmdletBinding()]
Param (
[string]$ConfigPath
)
$Replacements = @{
'##MY_CREDENTIALS_USERNAME##' = 'This is not my user name'
'##MY_CREDENTIALS_PASSWORD##' = 'This might be my password'
}
Write-Verbose "Starting to process $ConfigPath"
(Get-Content -Path $ConfigPath) | ForEach-Object {
$EachLine = $_
$Replacements.GetEnumerator() | ForEach-Object {
if ($EachLine -match $_.Key)
{
Write-Verbose "Changing $EachLine to $($_.Value)"
$EachLine = $EachLine -replace $($_.Key), $($_.Value)
Write-Verbose "Line is now $EachLine"
}
}
$EachLine
} | Out-File $ConfigPath
Write-Verbose "Completed processing for $ConfigPath"