Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Octopus Deploy Post-Deploy script to update connectionString attributes within an ASP.Net web.config file
# The following two lines were for debugging purposes to simulate the variables which are made available
# by Octopus when it invokes this script
#$OctopusParameters = @{}
#$OctopusParameters["DatabaseContext"] = "Data Source=DatabaseServer;Initial Catalog=Database;Integrated Security=true"
# This function is included because this function doesn't always seem to be available
# on freshly installed web servers when Octopus is deploying to. It is used to get the
# location where the script file is located, to allow the web.config file in the same
# location to be accessed.
function Get-ScriptDirectory {
$invocation = (Get-Variable MyInvocation -Scope 1).Value
$script = [IO.FileInfo] $invocation.MyCommand.Path
if ([IO.File]::Exists($script)) {
return (Split-Path $script.Fullname)
} else {
return $null
$scriptDir = Get-ScriptDirectory
$webConfig = New-Object XML
#$webConfig = (Get-Content "$scriptDir\web.config")
#$webConfig = [xml](Get-Content "$scriptDir\web.config")
# Iterate over each connection string within the web.config file
$webConfig.configuration.connectionStrings.add | ForEach-Object {
# If the current connectionString name attribute is a valid key
# within the variables hash table then update the connectionString
# attribute.
if($OctopusParameters[$] -ne $null){
Write-Host $OctopusParameters[$]
$_.connectionString = $OctopusParameters[$]
# This else is optional as within our scenario some connection strings are not
# not required on some deployment servers, so if they are not listed within
# Octopus' variables, the connectionString is deleted from web.config.
#Connection string does not exist in OctopusParameters, delete from web.config
$node = $_
# Save the updated file from memory back to disk.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment