powershell - 试图用 ";"替换变量中的字符串

标签 powershell powershell-3.0

我认为这是一个简单的问题,但我还没有找到解决方案,并且花了几个小时试图弄清楚为什么它不起作用。

在一个变量中我有一个字符串:_webconfig = new Object(); 我想在一些文本之后插入一行。

我尝试使用 -replace 来做到这一点,但它无法正常工作,因为该函数将“命中”不止一次,导致模式 x2。

由于 $pattern 变量末尾的 ;,这是我现在使用的代码(不起作用):

 $Pattern = "_webconfig = new Object();"
 $replaceWith =  "$Pattern `n_webconfig.$key = `"$value`";"       

 # write-Host "Pattern: $Pattern, replaceWith: $replaceWith"
 $text= $text -replace $pattern, $replaceWith
  • 末尾的变量$text会是js文件,每行末尾需要有;

我想要的结果是:

_webconfig = new Object();

将变成:

_webconfig = new Object();
_webconfig.env = "dev";
_webconfig.ServicesAppName= "Services";
  • 包含正确值的“键”和“值”。

我怎样才能做到这一点?

最佳答案

可能您所要做的就是转义您的 regex 字符串,因为有两个括号:

$Pattern = "_webconfig = new Object();"
$replaceWith =  "$Pattern `n_webconfig.$key = `"$value`";"       

$text= $text -replace [regex]::Escape($pattern), $replaceWith

关于powershell - 试图用 ";"替换变量中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37705268/

相关文章:

regex - 替换 ini 文件中的 block 文本

powershell - 有没有办法通过 start-process 将可序列化对象传递给 PowerShell 脚本?

powershell - 如何使用 PowerShell 下载 protected 文件?

Powershell - 计算字符串中某些内容的X个数

azure - powershell 将 blob 上传到 azure blob 存储设置内容类型

powershell - PowerShell 中的代理函数不接受管道输入

c# - 自定义 PowerShell 管理单元 : custom format doesn't work

powershell - 使用比较对象在Powershell中比较CSV文件

c# - 使用 powershell 脚本通过 c# 重新启动应用程序池

uwp - 使用Powershell启动Metro风格的应用程序