Sunday, May 8, 2016

PowerShell v2 Replace Does not Like FilePaths with Slashes

,
In a recent script I needed to swap out a portion of a filepath with another. "Great", I thought, "-replace to the rescue." Wrongo. After I tried this out
c: est -replace c: est,D: est
and got no changes,
c: est
I recalled some issues with slashes and replace which led me to run this test:

c: est -replace c:test,D: est
 successfully I might add:

D: est 
So, I started looking for a workaround.
In case you are wondering why this is the case, -replace works with the regular expression engine and , without any other characters following it, is an escape character. To properly deal with this you need a in each place where a would normally be to be handled by -replace.

Thankfully, the .NET class

String.Replace Method (String, String)
allows me to play much more nicely than the -replace operator.  For instance, if I do this:
$string = C: est est.txt
$string.Replace(C: est,D: est)
it works:
D: est est.txt
However, this is the ugly way around the block. Here are a few alternatives:
($string = C: est est.txt).Replace(C: est,D: est)
D: est est.txt
To show its still the same old thing (and only the interpreted value was manipulated) look at the variable.
$string
C: est est.txt
If you want to simplify it without retaining the original value, just update the string (or variable) directly:
C: est est.txt.Replace(C: est,D: est)
D: est est.txt
So, in this scenario, I just decided to use the .NET method over the -replace operator to get around the issue quickly and cleanly. There are many other ways you can slice this, but, I wanted to note it for others who ran into issues with -replace and file paths.

0 comments to “PowerShell v2 Replace Does not Like FilePaths with Slashes”

Post a Comment

 

Computer Info Copyright © 2016 -- Powered by Blogger