14

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

2 Answers 2

31

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

Sign up to request clarification or add additional context in comments.

1 Comment

:) When I didn't kwnow about this method the code was complicated (escaping regex sensitive characters by hand). This method pays off ;)
17

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.