Instantly share code, notes, and snippets.

Embed
What would you like to do?
PowerShell script to update an app.config file based on a parameters.xml
function Update-AppConfig
{
[cmdletbinding()]
param
(
[parameter(Mandatory = $true, HelpMessage = "Name of app.exe.config file")]
[string]$AppConfigFile,
[parameter(Mandatory = $false, HelpMessage = "Name of parameters.xml file")]
[string]$ParametersFile = "parameters.xml"
)
if (-not (test-path $AppConfigFile)) {
Write-Error -Message "The application configuration $AppConfigFile was not found"
Return $null
}
if (-not (test-path $ParametersFile)) {
Write-Error -Message "The application configuration $ParametersFile was not found"
Return $null
}
[xml]$ParametersXml = Get-Content -Path $ParametersFile -Raw
[xml]$AppConfigXml = Get-Content -Path $AppConfigFile -Raw
Write-Verbose -Message "Using xpath to update values in '$AppConfigFile."
Foreach ($Node in $ParametersXml.Parameters.parameter) {
Write-Verbose -Message " Updating '$($Node.ParameterEntry.Match)' with value '$($Node.DefaultValue)'."
if ($Node.ParameterEntry.Match.endswith("/text()"))
{
$AppConfigXml.SelectSingleNode($Node.ParameterEntry.Match).InnerText = $Node.DefaultValue
} else
{
$AppConfigXml.SelectSingleNode($Node.ParameterEntry.Match).'#text' = $Node.DefaultValue
}
}
Write-Verbose -Message "Saving updated configuration."
$AppConfigXml.Save((Resolve-Path $AppConfigFile))
}
Update-AppConfig -AppConfigFile MyApp.exe.config -Verbose
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment