string - 包括传递字符串:Powershell脚本中-Replace Variable的符号

标签 string powershell replace literals

$FilePath = 'Z:\next\ResourcesConfiguration.config'
$oldString = 'Z:\next\Core\Resources\'
$NewString = 'G:\PublishDir\next\Core\Resources\'

任何想法如何替换具有:的字符串。我想更改配置文件中的路径。简单的代码对此不起作用。尝试以下
(Get-Content $original_file) | Foreach-Object {
 $_ -replace $oldString, $NewString
 } | Set-Content $destination_file

最佳答案

Replace运算符采用正则表达式模式,“\”在正则表达式中具有特殊含义,它是转义符。您需要将每个反斜杠加倍,或者最好使用转义方法:

$_ -replace [regex]::escape($oldString), $NewString

或者,您可以使用string.replace方法,该方法采用字符串并且不需要特别注意:
$_.Replace($oldString,$NewString)

关于string - 包括传递字符串:Powershell脚本中-Replace Variable的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12492987/

相关文章:

objective-c - CamelCase 到下划线并返回到 Objective-C

powershell - 使用 Powershell 更改区域设置

powershell - 计算Powershell数组中的行数

javascript - 如何使用 Javascript 替换特定网站的 href 链接?

c# - 查找并替换文件中的数据(不加载整个文件)?

python - 我的数据集显示一个字符串,而它应该是一个大括号集/字典

c# - 在 C# 中比较字符串和对象

string - 是否可以将短子字符串与散列长字符串进行比较

PowerShell 函数

mysql - 替换 & 符号