Skip to content

Instantly share code, notes, and snippets.

@MartynJones87
Created September 20, 2012 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MartynJones87/3755529 to your computer and use it in GitHub Desktop.
Save MartynJones87/3755529 to your computer and use it in GitHub Desktop.
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.Load("$scriptDir\web.config")
#$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[$_.name] -ne $null){
Write-Host $OctopusParameters[$_.name]
$_.connectionString = $OctopusParameters[$_.name]
}
# 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.
else{
#Connection string does not exist in OctopusParameters, delete from web.config
$node = $_
$node.ParentNode.RemoveChild($node)
}
}
# Save the updated file from memory back to disk.
$webConfig.Save("$scriptDir\web.config")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment