我正在尝试使用PowerShell通过新值自动更新web.config
文件中的数据源。
这是我的连接字符串:
<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
运行上述脚本时出现以下错误。
The regular expression pattern "Data Source=(local)\abc; Trusted_Connection=True; Persist Security Info=True; Enlist=true; Initial Catalog=abcLogDB" is not valid. At line:5 char:1 + $value = $value -replace "$oldstring","$newstring" | Set-Content -Pas ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: ("Data Source=(l...og=OnityLogDB" :String) [], RuntimeException + FullyQualifiedErrorId : InvalidRegularExpression
答案 0 :(得分:0)
欢迎来到StackOverflow,Hari Krishna!您的脚本中发生了一些事情。
新旧字符串中的引号过多-找不到旧字符串。通常,除非使用嵌入的$variableName
来扩展其值,否则应使用单引号。
括号被视为正则表达式特殊字符,因为您使用的是-replace
语法。 [string]
对象的.Replace
方法可用于不带正则表达式的简单替换。
Set-Content
命令不知道要对哪个文件进行操作。但是,您实际上并不想将文件的内容设置为仅$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
编辑:更正了在其他测试中发现的问题。