首页 > 解决方案 > Powershell -replace 当替换字符串包含 $+

问题描述

我正在 PowerShell 中进行字符串替换。我无法控制要替换的字符串,但我可以通过这种方式重现我遇到的问题:

> 'word' -replace 'word','@#$+'
@#word

当我需要的实际输出是

> 'word' -replace 'word','@#$+'
@#$+

字符串$+被扩展为被替换的单词,我无法找到阻止这种情况发生的方法。我尝试使用反引号(就像正常的 PowerShell 方式一样)转义$with \(好像它是一个正则表达式)。`例如:

> 'word' -replace 'word',('@#$+' -replace '\$','`$')
@#`word

如何$+在 PowerShell 中用文字替换?对于它的价值,我正在运行 PowerShell Core 6,但这也可以在 PowerShell 5 上重现。

标签: powershellreplacestring-literals

解决方案


-replace您可以使用如下.Replace()方法,而不是使用运算符:

PS> 'word'.Replace('word','@#$+')
@#$+

.Replace()方法来自 .NET String 类,而-Replace运算符是使用 .NET 实现的System.Text.RegularExpressions.Regex.Replace()

更多信息:https ://vexx32.github.io/2019/03/20/PowerShell-Replace-Operator/


推荐阅读