2010-02-25 110 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的