Skip to content

Instantly share code, notes, and snippets.

@jwcarroll
Created March 5, 2012 20:56
Show Gist options
  • Save jwcarroll/1981023 to your computer and use it in GitHub Desktop.
Save jwcarroll/1981023 to your computer and use it in GitHub Desktop.
Set Connection String Powershell Function
Function Set-ConnectionString{
[CmdletBinding(SupportsShouldProcess=$True)]
Param(
[string]$fileName="app.config",
[string]$connectionStringName,
[string]$connectionString
)
$config = [xml](Get-Content -LiteralPath $fileName)
$config.Configuration.connectionStrings
$connStringElement = $config.SelectSingleNode("configuration/connectionStrings/add[@name='$connectionStringName']")
if($connStringElement) {
$connStringElement.connectionString = $connectionString
if($pscmdlet.ShouldProcess("$fileName","Modify app.config connection string")){
Write-Host ("Updating app.config connection string {0} to be {1}" -f $connectionStringName, $connectionString)
$config.Save($fileName)
}
}
else{
Write-Error "Unable to locate connection string named: $connectionStringName"
}
}
@jwcarroll
Copy link
Author

You can call it like this:

Set-ConnectionString "MyWebApp\app.config" MyConnectionString "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment