在Powershell字符串中替换路径

13

在我的脚本中,我检查一些文件,并想要用另一个字符串(相应共享的UNC路径)替换它们的完整路径的一部分。

例如:

$fullpath = "D:\mydir\myfile.txt"
$path = "D:\mydir"
$share = "\\myserver\myshare"
write-host ($fullpath -replace $path, $share)

由于$path不包含正则表达式的有效模式,所以最后一行代码会出错。

我该如何修改这行代码,使得替换操作符将变量$path中的内容作为文本处理?

提前感谢, Kevin

2个回答

31

使用[regex] :: Escape() - 非常方便的方法

$fullpath = "D:\mydir\myfile.txt"
$path = "D:\mydir"
$share = "\\myserver\myshare"
write-host ($fullpath -replace [regex]::Escape($path), $share)

你也可以使用我的过滤器rebase来完成它,参考Powershell: subtract $pwd from $file.Fullname


当我不知道这个方法时,代码很复杂(手动转义正则表达式敏感字符)。这种方法非常值得 ;) - stej

17

方法$variable -replace $strFind,$strReplace可以理解正则表达式模式。
但是方法$variable.Replace($strFind,$strReplace)不行。所以尝试使用前者。

PS > $fullpath.replace($path,$share)  

\myserver\myshare\myfile.txt


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接