PowerShell 在文件行为中查找并替换为正则表达式

PowerShell find and replace with regex in file behavior

我正在尝试使用 PowerShell 查找和替换连接字符串。这是正则表达式:https://regex101.com/r/onyJZz/1 找到我需要的。

我要修改的配置文件内容如下:

<connectionStrings>
  <add name="FrameworkEntities" connectionString="metadata=res://*/PortalEntities.csdl|res://*/PortalEntities.ssdl|res://*/PortalEntities.msl;provider=System.Data.SqlClient;
       provider connection string=&quot;data source=someservername.domain.co;initial catalog=Portal;persist security info=True;user 
id=user;password=user$ecurity;MultipleActiveResultSets=True;App=EntityFramework;" providerName="System.Data.EntityClient" />
</connectionStrings>

基本上需要替换连接字符串的整个值。这是我正在做的事情的要点

$regex = '(?<=\bconnectionString=")[^"]*'
$dbname = 'newserver.domain.co' 
$user = 'sa'
$password = 'password2'
$catalog = 'Portal'
$frameworkdbpath = 'c:\folder\db.config'

$finalString = "metadata=res://*/PortalEntities.csdl|res://*/PortalEntities.ssdl|res://*/PortalEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=$dbname;initial catalog=$catalog;persist security info=True;user id=$user;password=$password;MultipleActiveResultSets=True;App=EntityFramework;"

(Get-Content $frameworkdbpath) | ForEach-Object {
    $_ -replace $regex, $finalString
} | Set-Content $frameworkdbpath

当 运行 上述代码时,替换仅适用于第一个分号。字符串的其余部分仍然存在,我不知道为什么。

您的连接字符串跨多行。 Get-Content returns 内容为行数组,每行单独处理。因此,您的连接字符串的第二行和第三行与您的表达式不匹配。

错误的解决方案: 在应用正则表达式之前将文件读入单个字符串。您还可以删除 ForEach-Object.

(Get-Content $frameworkdbpath -Raw) -replace $regex, $finalString |
    Set-Content $frameworkdbpath

好的解决方案:你的输入数据是XML,所以应该这样处理。

[xml]$xml = Get-Content $frameworkdbpath
$node = $xml.SelectSingleNode('/connectionStrings/add')
$node.connectionString = $finalString
$xml.Save($frameworkdbpath)