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
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') .
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.
You can use "\\r\\n" also for the new line in powershell .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With