How to escape PowerShell double quotes from a .bat file

前端 未结 2 569
深忆病人
深忆病人 2020-12-19 23:23

I\'m trying to replace all double quotes in a file (temp1.txt) with two double quotes using this PowerShell command run from a bat file in Windows 7:

powersh         


        
相关标签:
2条回答
  • 2020-12-20 00:12

    Hm, here you need to escape the " on the command line, inside a double quoted string. From my testing, the only thing that seems to work is quadruple double quotes """" inside the quoted parameter:

    powershell.exe -command "echo '""""X""""'"
    

    So then your command line should be:

    powershell -Command "(gc c:\temp\temp1.txt) -replace '""""', '""""""""' | Out-File -encoding UTF8 c:\temp\temp2.txt"
    

    There is another way to handle this with PowerShell, assuming you don't want to just put these commands in a file and call it that way: use -EncodedCommand. This lets you base64 encode your entire command or script and pass it as a single parameter on the command line.

    So here's your original command:

    (gc c:\temp\temp1.txt) -replace '"', '""' | Out-File -encoding UTF8 c:\temp\temp2.txt
    

    Here's a script to encode it:

    $c = @"
    (gc c:\temp\temp1.txt) -replace '"', '""' | Out-File -encoding UTF8 c:\temp\temp2.txt
    "@
    $b = [System.Text.Encoding]::Unicode.GetBytes($c)
    $e = [System.Convert]::ToBase64String($b)
    

    $e now contains:

    KABnAGMAIABjADoAXAB0AGUAbQBwAFwAdABlAG0AcAAxAC4AdAB4AHQAKQAgAC0AcgBlAHAAbABhAGMAZQAgACcAIgAnACwAIAAnACIAIgAnACAAfAAgAE8AdQB0AC0ARgBpAGwAZQAgAC0AZQBuAGMAbwBkAGkAbgBnACAAVQBUAEYAOAAgAGMAOgBcAHQAZQBtAHAAXAB0AGUAbQBwADIALgB0AHgAdAA=

    So your new command line can be:

    powershell.exe -encodedCommand KABnAGMAIABjADoAXAB0AGUAbQBwAFwAdABlAG0AcAAxAC4AdAB4AHQAKQAgAC0AcgBlAHAAbABhAGMAZQAgACcAIgAnACwAIAAnACIAIgAnACAAfAAgAE8AdQB0AC0ARgBpAGwAZQAgAC0AZQBuAGMAbwBkAGkAbgBnACAAVQBUAEYAOAAgAGMAOgBcAHQAZQBtAHAAXAB0AGUAbQBwADIALgB0AHgAdAA=
    

    There is no need to worry about escaping anything.

    0 讨论(0)
  • 2020-12-20 00:12

    The escape character is grave-accent for PowerShell. Try this instead:

    powershell -Command "(gc c:\temp\temp1.txt) -replace `", `"`" | Out-File -encoding UTF8 c:\temp\temp2.txt"
    
    0 讨论(0)
提交回复
热议问题