PowerShell更新连接字符串

时间:2009-08-15 08:20:22

标签: linq entity-framework powershell connection-string app-config

我有以下脚本,它将更新开发中使用的三个不同配置文件的连接字符串。

function Main()
{   
pushd
cd ..
$aomsDir = pwd
$configFiles = @( 'util\GeneratePocos.exe.config', 'src\Web.UI\web.config', 'src\Data\App.Config')

$MyAOMSEntitiesConnStr = $env:AOMS_CONN_STR

Write-Host 'Beginning update of Connection strings...'

foreach($file in $configFiles)
{
    $config = New-Object XML
    $config.Load("$aomsDir\$file")

    foreach($conStr in $config.configuration.connectionStrings.add)
    {
        if($conStr.name -ieq 'AOMSEntities')
        {
            $conStr.connectionString = $MyAOMSEntitiesConnStr
        }
    }

    $config.Save("$aomsDir\$file")
}

Write-Host 'Completed updating connection strings for your machine.'

popd

}

主要

问题是连接字符串需要包含“e;但是当保存配置文件时,它变为& quote;因此连接字符串不再有效。

有没有人知道这样做的方法,我考虑过对文件进行文本替换,但也许有更清洁的方法。

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

这一行解决了我的问题:

(Get-Content "$aomsDir\$file") | % {$_ -replace '"', '"'} | Set-Content -path "$aomsDir\$file"

它将确保“写入配置文件并允许应用程序连接到数据库。

答案 1 :(得分:1)

对于嵌入在双引号分隔属性值中的双引号,这是预期的。您可以使用单引号代替,例如“E; (还是那个'e :)?

此外,您可以简化将XML加载到的方式:

[xml]$config = Get-Content "$aomsDir\$file"

答案 2 :(得分:0)

我认为您应该使用System.Configuration程序集访问连接字符串。我写了一篇关于如何在构建项目时使用powershell加密连接字符串的帖子:Encrypt App.config section using PowerShell as a Post-build event。你必须调整它,因为你的目标不是加密,但它应该对你有帮助。