Skip to content

Instantly share code, notes, and snippets.

@markarnott
Created September 6, 2017 15:02
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save markarnott/c4aec1fc544fe89e2bd21f3f00d78933 to your computer and use it in GitHub Desktop.
Save markarnott/c4aec1fc544fe89e2bd21f3f00d78933 to your computer and use it in GitHub Desktop.
A powershell script to inject environmentVariable elements into aspNetCore Element in web.config for ASP.NET Core Module
#
# == Turn This ==
# <?xml version="1.0" encoding="utf-8"?>
# <configuration>
# <system.webServer>
# <handlers>
# <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
# </handlers>
# <aspNetCore processPath=".\MyCoreGizmo.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
# </system.webServer>
# </configuration>
#
# == Into This ==
#
# <?xml version="1.0" encoding="utf-8"?>
# <configuration>
# <system.webServer>
# <handlers>
# <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
# </handlers>
# <aspNetCore processPath=".\MyCoreGizmo.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout">
# <environmentVariables>
# <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
# </environmentVariables>
# </aspNetCore>
# </system.webServer>
# </configuration>
param(
[string] $WebConfigPath = ".\web.config",
[string] $EnvironmentName = "Development"
)
$WebConfigXml = [xml](Get-Content $WebConfigPath -Encoding "UTF8")
$EVarsParent = $WebConfigXml.CreateElement("environmentVariables")
$EVarChild = $WebConfigXml.CreateElement("environmentVariable")
$EVarChild.SetAttribute("name", "ASPNETCORE_ENVIRONMENT")
$EVarChild.SetAttribute("value", $EnvironmentName)
$EVarsParent.AppendChild($EVarChild) | Out-Null
$AspNetCoreNode = $WebConfigXml.SelectSingleNode("/configuration/system.webServer/aspNetCore")
$AspNetCoreNode.AppendChild($EVarsParent) | Out-Null
# How to keep 'pretty print' formatting is a conundrum
$PrettyXml = $WebConfigXml.Save([Console]::Out) # This converts encoding='utf-8' to encoding='IBM437'
Write-Output $PrettyXml
# This loses indentation and line breaks, but preserves the xml encoding
Set-Content -Path $WebConfigPath -Value $WebConfigXml.OuterXml -Encoding "UTF8"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment