Tuesday, June 28, 2011

Replacing a backslash with a foreslash in PowerShell

Using the title Replacing “\” with “/” is not very search friendly so we talk of fore- and back- slashes instead.

This is an interesting a quick exercise in RegEx (I had no idea I was getting tangled up in this) syntax.

Lets begin with a path:  $myPath = (${env:ProgramFiles(x86)} + "\MyStuff")

This returns:  C:\Program Files (x86)\MyStuff

Now, I have an Apache config file, so I need to turn those “\” into Linux happy “/”

I first try: $myPath = $myPath -replace "\", "/"  and get the error: Invalid regular expression pattern: \.

Off to search land I go.  Oh, regular expressions, I remember this and I dutifully double escape both my slashes (just like I have to in scripts).  The command now looks like this:  $myPath = $myPath -replace "\\", "//"

No error had.  I return the string and I get C://Program Files (x86)//MyStuff    whoops.

Now.  The error was specific to the find side of the command, not the replace side.  So, to make this correct:  $myPath = $myPath -replace "\\", "/"

1 comment:

Anonymous said...

Thanks for sharing this. Was having trouble finding a string "\FolderName\" and replacing it with "\NewFolderName\".

And I didn't realize til I ran my script that the replace string isn't a reg expr.

So, my replace looked like this:

$source = $source -replace "\\FolderName\\", "\NewFolderName\".

Thanks again !