Created
April 15, 2015 13:28
-
-
Save bradymholt/d5305e5ee2e0d5623888 to your computer and use it in GitHub Desktop.
Set-ConnectionStringDatabase for Package Manager Console - updates database name in connection string across all projects in solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Set-ConnectionStringDatabase { | |
Param( | |
[string]$DatabaseName, | |
[string]$ConnectionStringName='DBConnectionString' | |
) | |
Function Set-ConnectionString{ | |
Param( | |
[string]$ConfigFile, | |
[string]$ConnectionStringName, | |
[string]$DatabaseName | |
) | |
[xml] $config = Get-Content $ConfigFile | Out-String | |
$connStringElement = $config.SelectSingleNode("//connectionStrings/add[@name='$ConnectionStringName']") | |
if($connStringElement) { | |
$connStringElement.connectionString = $connStringElement.connectionString -Replace "database=[\w\-]+|initial catalog=[\w\-]+", "DATABASE=${DatabaseName}" | |
# Set up formatting | |
$xwSettings = new-object System.Xml.XmlWriterSettings | |
$xwSettings.indent = $true | |
$xmlWriter = [Xml.XmlWriter]::Create($ConfigFile, $xwSettings) | |
$config.Save($xmlWriter) | |
Write-Host "Updated connection string '$ConnectionStringName' in $ConfigFile" | |
} | |
} | |
Get-Project -All | ForEach-Object -Process { | |
$currentFolder = (Split-Path $_.FullName) | |
$file = "${currentFolder}\web.config" | |
If (!(Test-Path $file)){ | |
$file = "${currentFolder}\app.config" | |
} | |
If (Test-Path $file){ | |
Set-ConnectionString -ConfigFile $file -ConnectionStringName $ConnectionStringName -DatabaseName $DatabaseName | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment