xml - 如何在 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
解决方案
欢迎来到 StackOverflow,Hari Krishna!您的脚本发生了一些事情。
您的旧字符串和新字符串中有太多引号 - 将找不到旧字符串。一般来说,应该使用单引号,除非有一个嵌入
$variableName
的要扩展它的值。括号被视为正则表达式特殊字符,因为您使用的是
-replace
语法。该[string]
对象的.Replace
方法可用于没有正则表达式的简单替换。该
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
编辑:更正了在附加测试期间发现的问题。
推荐阅读
- python - If 语句和变量
- java - 我如何接收数据
- node.js - TypeError: 'connect' 只接受回调
- json - 如何根据json值firebase实时数据库使单元格自行删除
- python - 如何获取格式以不导致类型提示错误?
- c# - 设置参考号并将其与文本文件中的其他数据进行比较
- arrays - 多个条件 INDEX MATCH 公式的问题
- spring-boot - Couchbase & Spring boot - DefaultOrphanResponseReporter - 观察到孤儿响应
- css - 如何对整个页面的元素只应用一次样式?
- android - 每次如何在koin中创建viewModel的新实例