Escape back slash next to double quote in PowerShell failing

I'm running PowerShell in a batch file to replace characters and I'm stuck trying to replace instances of \" with ".

\ on its own can be escaped by doing \\

" on its own can be escaped by doing """"

Those work but if there's a back slash next to a double quote, this doesn't work: \\""""

Is it possible to do this, still using PowerShell in a batch file?

2

1 Answer

Since the -Replace operator works matching regex patterns, you can use the [ ] square bracket and put the escaped characters in two separate sets for the value to be escaped and replaced i.e. '[\\][""]'.

You can use '""""' for the single double quote replacement characters of the two to replace. So it's look like so basically: (Get-Content $_) -replace '[\\][""]', '""""'.

Please note that -replace '[\\][""]', '""""' assumes you want to replace \" with just " but you can change it to -replace '[\\][""]', '#' to replace \" with # like that if needed for example.

Working Full Command Line Syntax

start /wait /min Powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "Get-ChildItem '*.txt' | ForEach-Object {(Get-Content $_) -replace '[\\][""]', '""""' | Set-Content $_.FullName}"

Troubleshooting detail...

I used this syntax for a single file to start

Powershell.exe -ExecutionPolicy Bypass -Command "Get-ChildItem 'C:\Folder\test.txt' | ForEach-Object {(Get-Content $_) -replace '[\\][""]', '"""' }"

Once I ironed out at this level, I moved on to the full command and ran it against a single file still and kept checking it per each run until I figured out what was needed to get the final desired result.

Supporting Resource

3

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

You Might Also Like