May 28, 2009

Replace macro fields with powershell

Have you ever needed to update config files when moving from dev to qa and then finally to prod? One simple way of doing this is with powershell and this can than be called out from a nant script if you like. You will need to template your config files (or .xml files, or any file with any extension) and then have a corresponding value to update it with.

Here is a little snippet, update to suit your needs:

templates\AppSettings.config

<add key="MyKey" value="$foo" />
ConfigValues.ps1

$foo = 'MyValue'
run.ps1

$currentDir = (Get-Location -PSProvider FileSystem).ProviderPath
$currentDir

# Load the variables and values to our current scope
. ($currentDir + "/ConfigValues.ps1")

# Process all files in templates folder
foreach ($file in (dir "templates/*.*"))
{
$text = [IO.File]::ReadAllText($file)
$ExecutionContext.InvokeCommand.ExpandString($text) | out-file (Join-Path $pwd $file.name)
}
Write-Host "Done."

Things in powershell can be written very quickly and this is a great example.

No comments:

Post a Comment