I am replacing text using powershell running in a batch file, using single quotes to enclose the text to be replaced.

I have found that trying to escape a comma followed by a double quote, can't be done the usual way.

The , character on its own is escaped by using ","

The " character on its own is escaped by using """"

The above works if " and , are not next to each other, but if they are, like this...

", 

Using this to escape both characters, doesn't work:

'""""","' 

That's four double quotes to escape the " character, then two more to escape the , character, enclosed in single quotes.

Please don't suggest to use powershell on its own, I want to keep this the way it is, running from a batch file.

Everything else works perfectly, it's just this ", issue.

Cheers.

1

2 Answers

OK I worked this out, it needs the last double quote removing, which seems bizarre to me because it's breaking the rules about escaping special characters, but that's what works. Maybe it's because I'm running powershell in a batch file (where a back tick is useless even though I am using powershell).

'"""",' 

This also works when there's characters again after the comma.

For example the above will work for this:

some text", then some more text 

Changing it to this:

some text then some more text 

In Powershell you can use strings in 2 ways.

"...." and '....'.

When you use the first, the second quote char does not have to be escaped. If you use the second, the first quote char does not have to be escaped. Eg: "This is a 'test'" and 'This is a "test" too.'

In addition, '...' is literal text, so '$test' will literally print $test whereas "$test" will print whatever is in the variable $test.

Escaping a string can be done in multiple ways, \" is such way. "This is a test $('"') too" is another.

I find that it usually helps to use whatever looks best depending on the code surrounding it.

Because you are combinding batch scripting and powershell, "" will work as it is the batch way to escape ", but this will give weird results and its encouraged to not use this. It is therefor advised to not use batch at all and do everything in PowerShell directly.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy