目标:在 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/