简体   繁体   中英

Replace path in Powershell string

in my script I check some files and would like to replace a part of their full path with another string (unc path of the corresponding share).

Example:

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

The last line gives me an error since $path does not not contain a valid pattern for regular expressions.

How can I modify the line to make the replace operator handle the content of the variable $path as a literal?

Thanks in advance, Kevin

Use [regex]::Escape() - very handy method

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

You might also use my filter rebase to do it, look at Powershell: subtract $pwd from $file.Fullname

The method $variable -replace $strFind,$strReplace understands regex patterns.
But the method $variable.Replace($strFind,$strReplace) does not. So try this one.

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

\\myserver\\myshare\\myfile.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM