首页 > 解决方案 > 如何在 XML 文件中使用 PowerShell 更新数据源连接字符串

问题描述

我正在尝试web.config使用 PowerShell 自动使用新值更新文件中的数据源。

这是我的连接字符串:

<connectionStrings>
    <add name="abcLogging" connectionString="Data Source=(local)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB" providerName="System.Data.SqlClient" />
</connectionStrings>

PowerShell 脚本:

$newstring = '"Data Source=(test)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB" '
$oldstring = '"Data Source=(local)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB" '
$XmlDocument = [xml](Get-Content "D:\abc\Web.config");
$value = $XmlDocument.configuration.connectionStrings.add.connectionstring 
$value = $value -replace "$oldstring","$newstring" | Set-Content -PassThru 

运行上述脚本时出现以下错误。

正则表达式模式“Data Source=(local)\abc; Trusted_Connection=True;
持久安全信息=真;征募=真;初始目录=abcLogDB”无效。
在行:5 字符:1
+ $value = $value -replace "$oldstring","$newstring" | 设置内容-Pas ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: ("Data Source=(l...og=OnityLogDB" :String) [], RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression

标签: xmlstringpowershellconnection

解决方案


欢迎来到 StackOverflow,Hari Krishna!您的脚本发生了一些事情。

  1. 您的旧字符串和新字符串中有太多引号 - 将找不到旧字符串。一般来说,应该使用单引号,除非有一个嵌入$variableName的要扩展它的值。

  2. 括号被视为正则表达式特殊字符,因为您使用的是-replace语法。该[string]对象的.Replace方法可用于没有正则表达式的简单替换。

  3. Set-Content命令不知道要对哪个文件进行操作。但是您并不想将文件的内容设置为 only $value。这将为您提供一个没有任何 XML 内容而只有连接字符串的文件。

这是一个应该做你想做的脚本:

$configFile = 'C:\temp\web.config'

Set-Content -Path $configFile -Value @"
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
    <add name="abcLogging" connectionString="Data Source=(local)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
"@

$newstring = 'Data Source=(test)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB'
$oldstring = 'Data Source=(local)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB'

$XmlDocument = [xml](Get-Content $configFile);
$XmlDocument.configuration.connectionStrings.add | %{
    If($_.connectionString -eq $oldstring){
        $_.connectionString = $newstring
    }
}
$XmlDocument.Save($configFile)
Get-Content -Path $configFile

编辑:更正了在附加测试期间发现的问题。


推荐阅读