views:

213

answers:

2

Hi everyone,

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

+3  A: 

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 http://stackoverflow.com/questions/2253159/powershell-subtract-pwd-from-file-fullname/2253565#2253565

stej
Thank you so much. Too easy :-)
jarod1701
:) When I didn't kwnow about this method the code was complicated (escaping regex sensitive characters by hand). This method pays off ;)
stej
A: 

Try with the Replace method:

PS > $fullpath.replace($path,$share)
\myserver\myshare\myfile.txt

Shay Levy