powershell - 字符串替换在运行时在 powershell 脚本中不起作用

标签 powershell

我有 powershell 文件,其中有如下变量声明行

[string] $global:myExePath = "\\myshare\code\scripts";

我想通过执行 powershell 脚本在运行时将 \\myshare\code\scripts 替换为 \\mynewshare\code1\psscript

我正在使用
获取内容$originalfile | ForEach-Object { $_ -replace "\\myshare\code\scripts", $mynewcodelocation.FullName } |设置内容($originalfile)

如果正在执行 { $_ -replace "scripts", $mynewcodelocation.FullName } 它工作正常,但不适用于 { $_ -replace "\\myshare\code\scripts", $mynewcodelocation.FullName }

这里出了什么问题?

最佳答案

“\”是一种特殊的正则表达式字符,用于转义其他特殊字符。您需要将每个反斜杠加倍以匹配一个反斜杠。

-replace "\\\\myshare\\code\\scripts",$mynewcodelocation.FullName 

当你不知道字符串的内容时,你可以使用 escape 方法来为你转义字符串:

$unc = [regex]::escape("\\myshare\code\scripts")
$unc
\\\\myshare\\code\\scripts

-replace $unc,$mynewcodelocation.FullName 

关于powershell - 字符串替换在运行时在 powershell 脚本中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18811284/

相关文章:

function - 传播执行状态

远程机器上的 Powershell Start-Process msiexec 不工作

powershell - Azure ARM DSC 规模集部署 - 无法找到脚本

sql-server - 将 CSV 从 PowerShell 导入到 SQL Server

c# - PowerShell commandlet 被调用但没有响应

powershell - 如何在导出为 CSV 之前向每一行添加日期/时间

powershell - 在 NuGet 包管理器控制台中列出特定包的所有可用版本

powershell - 更改工作流的 SerializationMethod

powershell - Powershell实现将数组传递给命令

c# - 从 C# 调用 Powershell 并处理异常