powershell - 用 Powershell 替换 XML 文件格式文件(.Config 文件)中的行字符串的问题

标签 powershell azure-devops

目标:在 server.config 文件中查找一行并使用 powershell 替换为其他一些值
我试图在该文件中找到的字符串:

<add key="ReportServerUrl" value="http://ADEVSQL14\SQL2016_INS1/ReportServer"></add>
要替换的字符串:
<add key="ReportServerUrl" value="http://ADEVSQL14/SQL2016_INS1/ReportServer"></add>
我试过的:
$filename = Get-Content "C:\target\Server.Config"
$filename -replace "<add key="ReportServerUrl" value="http://ADEVSQL14\SQL2016_INS1/ReportServer"></add>", "<add key="ReportServerUrl" value="http://ADEVSQL14/SQL2016_INS1/ReportServer"></add>"
我得到的错误:
    ...  "<add key="ReportServerUrl" value="http://ADEVSQL14\SQL2016_INS1/Rep 
Unexpected token 'ReportServerUrl" value="http://ADEVSQL14\SQL2016_INS1/ReportServer"></add>"' in expression o statement.
附加输入:虽然我想将此功能用作 Azure devops 管道中 powershell 步骤的一部分,但我正在命令行尝试它,但收到类似错误
有人可以建议吗。
更新 1:
在命令行下尝试,它成功执行但没有被替换。
  $filename = Get-Content "C:\target\Server.config" -Raw
$filename -replace '"http://ADEVSQL14\SQL2016_INS1/ReportServer"','"http://ADEVSQL14/SQL2016_INS1/ReportServer"'|Set-Content -Path C:\target\Server.config;

最佳答案

来自 docs :

<input> -replace <regular-expression>, <substitute>

这意味着您无法搜索包含在正则表达式中具有特殊含义的字符(如反斜杠)的文字字符串。这些字符必须通过在它们前面插入反斜杠来转义。
尝试这个:
$filename -replace '"http://ADEVSQL14\\SQL2016_INS1/ReportServer"','"http://ADEVSQL14/SQL2016_INS1/ReportServer"'
您也可以使用 Regex.Escape() 自动转义所有特殊字符的方法:
$searchStr = '"http://ADEVSQL14\SQL2016_INS1/ReportServer"'
$searchStrEscaped = [Regex]::Escape( $searchStr )

$filename -replace $searchStrEscaped, '"http://ADEVSQL14/SQL2016_INS1/ReportServer"'

关于powershell - 用 Powershell 替换 XML 文件格式文件(.Config 文件)中的行字符串的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65449003/

相关文章:

c# - 编写 Powershell 帮助文件

entity-framework - VSTS 构建如何为 EF Core 添加更新数据库命令 Code First

powershell - 如何在 Azure Devops 管道中以管理员权限运行 PowerShell 任务

azure - 使用 TFS 在 azure 中启动自动交换

powershell - 使用 Azure 资源管理器时如何获取 CustomScriptExtensions 的输出?

json - 如何为azure虚拟机创建数据盘?

string - Powershell,函数在连接字符串(参数)时添加尾随空格

file - 如何使用 PowerShell 删除空子文件夹?

azure-devops - 如何删除 config.cmd 挂起的 azagent?

azure - ARM 部署提到了 Azure 资源的大范围