Search code examples
powershellsingle-quotes

Replace single quote by two single quotes in a file with batch powershell command


I'm currently working on an automated setup program. It has to execute SQL command. I decided to create it with a simple batch file which allows me to use commands like sqlcmd or Powershell.

I'm working on a XML file that will get insert into another file. First, I have to replace some strings in it. I successfully used the -replace command like that :

powershell -Command "(gc source_file.xml) -replace 'utf-8', 'utf-16' | sc updated_file.xml"

Now, the updated_file.xml still contains single quotes that I'd like to replace by '' (two single quotes). I'd like to use the replace command again to make the substitution. I tried to escape the single quote character but it didn't work :

powershell -Command "(gc source_file.xml) -replace "`'", "`'`'" | sc updated_file.xml"

The error shows that the single quote isn't escaped. What's more, in my case, it seems that the replace command only reads string between single quotes. I also tried with a regex::Escape("`'") without success.

Do you have any idea ?

Thanks a lot !


Solution

  • try this:

    powershell -Command "(gc source_file.xml)  -replace 'utf-8', 'utf-16' -replace '''', '''''' | sc updated_file.xml"