Created
January 27, 2017 20:18
-
-
Save romipetrelis/167a6817dbdbd12e7080d1f0c4f248d7 to your computer and use it in GitHub Desktop.
Replace tokens in config file with values from environment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param( | |
$SourceFile, | |
$TokenStart = '__', | |
$TokenEnd = '__' | |
) | |
function Get-EnvironmentVariables | |
{ | |
$env = @{} | |
Get-ChildItem -Path env:* | ForEach-Object { | |
$item = $_ | |
#variable names come out of VSTS with underscores, even though we specify them with dots | |
#our config transforms also use dots | |
$key = $item.Key -replace '_','.' | |
If(-Not $env.ContainsKey($key)) { | |
$env.Add($key, $item.Value) | |
} | |
} | |
return $env | |
} | |
function Replace-Tokens | |
{ | |
param( | |
$SourceFile, | |
$TokenStart, | |
$TokenEnd | |
) | |
$content = Get-Content -Path $SourceFile | ForEach-Object { | |
$line = $_ | |
$TokenTable = Get-EnvironmentVariables | |
$TokenTable.GetEnumerator() | ForEach-Object { | |
$token = $_ | |
$key = $TokenStart + $token.Key + $TokenEnd | |
# case-insensitive match... | |
if ($line -match $key) { | |
$line = $line -replace $key, $token.Value | |
} | |
} | |
$line | |
} | |
Set-Content -Value $content -Path $SourceFile -Force | |
} | |
Replace-Tokens -SourceFile $SourceFile -TokenStart $TokenStart -TokenEnd $TokenEnd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment