powershell - Powershell:无效的正则表达式

标签 powershell file-io windows-xp

this发布中,我设法在Windows XP上用Powershell替换目录的子文件中的字符串。

foreach ($f in gci -r -include "*.bat") 
    { (gc $f.fullname) |
       foreach { $_ -replace "D:","C:\path" }  |
       sc $f.fullname 
    }

不幸的是,一些异常(exception)情况需要使用“C:\\”而不是“C:\”。

我试图使用以下命令解决此问题(将“C:\ path \\”替换为“C:\\ path \\”),但失败:
foreach ($f in gci -r -include "*.bat") 
    { (gc $f.fullname) |
       foreach { $_ -replace "C\path\\","C:\\path\\" }  |
       sc $f.fullname 
    }

错误是:
Invalid regular expression pattern: C:\path\\

为了避免该问题,我尝试了几种变体,但是都产生了相同的错误(替换上面的第3行):
foreach { $_ -replace "C:\path\\\\","C:\\path\\" } |
foreach { $_ -replace 'C:\path\\',"C:\\path\\" } |
foreach { $_ -replace "`C:\path\\","C:\\path\\" } |
foreach { $_ -replace 'C:\path\\\\',"C:\\path\\" } |

有什么想法吗?

最佳答案

对于重新规划,将“C:\ path \”替换为“C:\\ path \\”

使用

$_ -replace "c:\\path\\\\","c:\\path\\"

Match模式是正则表达式,并且'\'需要以'\'进行转义。
替换字符串只是一个字符串,不需要转义字符

关于powershell - Powershell:无效的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11369768/

相关文章:

windows - 如何根据列号分隔固定宽度的文本文件

java - 从文件系统中获取文件并将其作为 File 对象传递

asp.net - 为什么 while 循环中保留数组中的值? (VB.NET)

python - 有什么方法可以在Python 2.5上安装PyOpenCV或OpenCV?

winapi - WTSRegisterSessionNotification 有时在 XP home 启动时不起作用

regex - PowerShell-如何基于另一个文件中的内容更新文件

powershell - 提取 URL 的第一部分

java - jButton1ActionPerformed 和 jButton2ActionPerformed 如何共享 BufferedReader/BufferedWriter?

java - 无法访问 Java 创建的文件——有时

powershell - 在 powershell 工作流程中使用 AzureStorageContext