Escaping quotes in powershell.exe via command prom

2019-02-13 03:18发布

问题:

After viewing this post I am trying to escape quotes, but doing a backslash does not escape html quotes like this: <-- notice it's a right double quote unlike the normal ".

E.g:

Works fine:

powershell -noexit -command $str = \"hello '123' world\"; write-host $str

Does not work:

powershell -noexit -command $str = \"hello '123'” world\"; write-host $str

How can I escape this? Or better how do I escape ALL characters at once to get rid of this hassle!

回答1:

Use a backtick ` to escape your special double quote, so this:

powershell -noexit -command $str = \"hello '123'” world\"; write-host $str

becomes this:

powershell -noexit -command $str = \"hello '123'`” world\"; write-host $str

EDIT:

Option 1. If you prefer using here-strings, you can change the above to powershell -file and run your powershell script file. Use here-strings as much as you want there.

Option 2. If you prefer not to deal with your special quote character inside calling/processing application/script, you can switch to using single quotes instead. In this case you only need to escape your single quotes, by doubling them, like this:

powershell -noexit -command $str = 'hello ''123''” world'; write-host $str

Notice here I did not do anything to your double quote character, and it works just fine.

So your string replace code may become slightly easier to read and maintain, especially if the editor does not display this character correctly (like Powershell console does - it shows a regular double quote instead).



回答2:

  1. Start -command switch with ""
  2. Strings are recognized by surrounding a text with 4 times quotes at both sides: """" text """"

    Example:

    powershell.exe -command """""Recognized as string """""
    
    Output Stream:> Recognized as string
    
  3. For quotes in sub expressions double the quotes, that means 8 times quotes

    Example:

    powershell.exe -command """""""""How to quote in subexpression"""""""""
    
    Output Stream:> "How to quote in subexpression"
    


回答3:

Running this from a command prompt (and within PowerShell actually):

powershell -noexit -command { $str = "hello '123' world"; write-host $str }

generates:

hello '123' world

Does this do what you need?