Saurabh Shetty
Saurabh Shetty

Reputation: 1

Powershell replace function has escape characters

I am writing a batch script in which I am trying to replace a value in a prop file. I am using PowerShell for the replacement code as I couldn't find any comparable way to do in batch script.

powershell -Command "(gc %PROPFILEPATH%) -replace '%FTPoldfilepath%', '%FTPnewfile%' | Set-Content %PROPFILEPATH%"

The variables %PROPFILEPATH%, %FTPoldfilepath% and %FTPnewfile% contain double backslashes (Eg: C:\\testing\\feed)

I realize that backslashes need to be escaped, can anyone guide me how to implement the escape function here.

Upvotes: 0

Views: 561

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200393

For one thing, as @Xalorous mentioned, you'll have to use PowerShell syntax for accessing environment variables:

powershell -Command "(gc $env:PROPFILEPATH) -replace $env:FTPoldfilepath, $env:FTPnewfile | Set-Content $env:PROPFILEPATH"

Also, only the search string needs to be escaped, not the replacement string. You can use the Escape() method of the regex class for that:

powershell -Command "(gc $env:PROPFILEPATH) -replace [regex]::Escape($env:FTPoldfilepath), $env:FTPnewfile | Set-Content $env:PROPFILEPATH"

Escaping is required here, because the -replace operator treats the search string as a regular expression.

However, since you apparently want just a simple string replacement, not a regular expression match, you could also use the Replace() method of the source string:

powershell -Command "(gc $env:PROPFILEPATH) | % { $_.Replace($env:FTPoldfilepath, $env:FTPnewfile) } | Set-Content $env:PROPFILEPATH"

As a side note, since you're using PowerShell anyway, you should seriously consider writing the whole script in PowerShell. It usually makes things a lot easier.

Upvotes: 1

Jeter-work
Jeter-work

Reputation: 801

Use double backslashes. Does not hurt if they come through doubled, or even tripled.

You will need to use $ENV:PROFILEPATH, $ENV:FTPoldfilepath, and $ENV:FTPnewpath in place of %PROPFILEPATH%, '%FTPoldfilepath%', and '%FTPnewfile%'

If your goal is to load the current path, replace the old path with the new one and save the new path, consider doing so with a full script instead of a single command:

$oldftppath = 'c:\some\path'
$newftppath = 'c:\new\path'
$newpath = $ENV:PROFILEPATH.replace($oldftppath,$newftppath)

But then it gets tricky. If you need a persisent environment variable, you need to use .NET framework to set it. https://technet.microsoft.com/en-us/library/ff730964.aspx

[Environment]::SetEnvironmentVariable("TestVariable", "Test value.", "User")

So, using this syntax:

[Environment]::SetEnvironmentVariable("PROFILEPATH", "$newpath", "User")

Or it could be "machine" for the context.

Upvotes: 1

Related Questions