2010-02-25 68 views
9

我检查了一些文件,并希望用另一个字符串(相应共享的unc路径)替换其部分完整路径。在我的脚本中替换Powershell字符串中的路径

例子:

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

最后一行给我一个错误,因为$路径不不包含正则表达式的有效模式。

如何修改该行以使replace运算符将变量$ path的内容作为文字来处理?

由于提前, 凯文

回答

23

使用[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

+0

太谢谢你了。太容易了:-) – bitfrickler 2010-02-25 13:36:20

+0

:)当我没有知道这个方法的代码是复杂的(用手转义正则表达式敏感字符)。这种方法是值得的;) – stej 2010-02-25 13:54:18

9

$variable -replace $strFind,$strReplace理解正则表达式的方法图案。
但方法$variable.Replace($strFind,$strReplace)没有。所以试试这个。

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

\ MYSERVER \ myshare的\ myfile.txt的

相关问题