Skip to main content

PowerShell function to replace text/tokens in a file.

<#
.SYNOPSIS
    Replace text in file(s).

.PARAMETER Files
    A list of files to perform replace operations.

.PARAMETER Replacements.
    A hashtable. Keys are the text to replace. Values are replacements.

.EXAMPLE
    Edit-ReplaceTextInFile Program.cs @{'YOUR-PROJECT-ID', $env:GOOGLE_PROJECT_ID}
#>
function Edit-ReplaceTextInFile(
    [string[]][Parameter(Mandatory = $true, ValueFromPipeline = $true)] $Files,
    [hashtable][Parameter(Mandatory = $true)] $Replacements
) {
    foreach ($file in $files) {
        $content = Get-Content $file | ForEach-Object {
            $line = $_
            foreach ($key in $Replacements.Keys) {
                $line = $line.Replace($key, $Replacements[$key])
            }
            $line
        }
        $content | Out-File -Force -Encoding UTF8 $file
    }
}