Skip to content

Instantly share code, notes, and snippets.

@romipetrelis
Created January 27, 2017 20:18
Show Gist options
  • Save romipetrelis/167a6817dbdbd12e7080d1f0c4f248d7 to your computer and use it in GitHub Desktop.
Save romipetrelis/167a6817dbdbd12e7080d1f0c4f248d7 to your computer and use it in GitHub Desktop.
Replace tokens in config file with values from environment
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