替换Powershell字符串中的路径

bit*_*ler 12 regex powershell

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

例:

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

最后一行给出了一个错误,因为$ path不包含正则表达式的有效模式.

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

凯文,提前谢谢

ste*_*tej 27

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

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

您也可以使用我的过滤器rebase来执行此操作,查看Powershell:从$ file.Fullname中减去$ pwd


Sha*_*evy 12

该方法$variable -replace $strFind,$strReplace了解正则表达式模式.
但该方法$variable.Replace($strFind,$strReplace)没有.试试这个吧.

PS > $fullpath.replace($path,$share)  
Run Code Online (Sandbox Code Playgroud)

\ MYSERVER\myshare的\ myfile.txt的