Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 887
bitfrickler Avatar asked Feb 25 '10 11:02

bitfrickler


People also ask

How do you replace part of a string in PowerShell?

If the string-to-be-replaced isn't found, the replace() method returns nothing. You don't need to assign a string to a variable to replace text in a string. Instead, you can invoke the replace() method directly on the string like: 'hello world'. replace('hello','hi') .

How do I replace multiple characters in a string in PowerShell?

You can replace multiple characters in a string using PowerShell replace() method or PowerShell replace operator. If you are using the PowerShell replace() method, you can chain replace() method as many times to replace the multiple characters in the PowerShell string.

How do I replace a new line in PowerShell?

You can use "\\r\\n" also for the new line in powershell .


1 Answers

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

like image 119
stej Avatar answered Sep 21 '22 04:09

stej