powershell - 如何替换字符串中的$(data)?

标签 powershell replace

我有一个名为configuration.xml的配置文件,它看起来像:

<?xml version="1.0" encoding="utf-8" ?>
<Configuration xmlns="http://tempuri.org/Configuration.xsd">

  <Icons>
    <Icon name="about" file="$(data)\more\data\about.png" />
    <Icon name="help" file="$(data)\more\data\help.png" />
  </Icons>

</Configuration>
为了将这些配置文件部署到不同的环境中,我想使用Powershell脚本(当前为PowerShell 5.1),该脚本应使用实际路径$(data)替换environment\path\to\data
我的脚本的简短版本如下所示:
$file = Get-Item '.\configuration.xml'
    
$content = ($file | Get-Content)

# file="$(data)\more\data" => file="environment\path\to\data\more\data"
$content = $content -replace '$(data)', 'environment\path\to\data'

$content | Set-Content $file.FullName
我试图使用单引号对$进行转义,还尝试通过使用反引号对双引号进行转义。"`$(data)" ,但这不起作用。
也尝试使用unicode "$([char]0x0024)(data)"解决它不成功。
有人可以指出解决方案吗?

边注
我想更改$(data),但这是第3方库的一部分,我无法更改。第三方库使用$(data)替换路径,并且该路径在另一个文件中配置。在大多数情况下,它是完整的,但是在这种特殊的使用情况下,我必须为具有完整路径的某些实例/子配置配置它。

最佳答案

当使用-replace运算符时,正则表达式用于匹配字符串。正则表达式匹配的字符串被文字字符串替换,但有一些异常(exception)。通用语法如下:

$strings -replace $regex,$stringliteral

正则表达式必须遵循正则表达式转义规则,而不是PowerShell转义规则。正则表达式转义字符为\。由于$()是regex中的特殊字符,因此您的regex表达式需要为\$\(data\)。您可以通过regex Escape()方法自动为您完成此操作。
$file = Get-Item '.\configuration.xml'

$content = ($file | Get-Content)

$content = $content -replace [regex]::Escape('$(data)'), 'environment\path\to\data'

$content | Set-Content $file.FullName

关于powershell - 如何替换字符串中的$(data)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57415921/

相关文章:

.net - 如何将ManagementObjectCollection对象转换为Powershell可读的格式?

powershell - 如何在不扩展 token 的情况下获取 PATH 环境变量的值?

php - MYSQL 字符串替换列 PHP

vim - 如何在vim中替换~(波浪号)

javascript - jQuery 替换多次出现的子字符串/文本

powershell - MS Exchange 2010:cmdlet无法作为计划任务正确执行

azure - 如何使用 PowerShell 检索逻辑应用工作流设置?

c# - 无法使用 PowerShell 通过管道传输控制台应用程序的无限输出

jQuery 从字符串中删除 '-' 字符

regex - 如何用sed插入html标签?