【问题标题】:How to escape PowerShell double quotes from a .bat file如何从 .bat 文件中转义 PowerShell 双引号
【发布时间】:2015-10-13 01:48:26
【问题描述】:

我正在尝试使用从 Windows 7 中的 bat 文件运行的 PowerShell 命令将文件 (temp1.txt) 中的所有双引号替换为两个双引号:

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

我不断收到错误:

 'Out-File' is not recognized as an internal or external command.

当我更改命令以将字母“a”替换为字母“b”时,它可以正常工作,如下所示:

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

我需要转义双引号,因为整个 powershell -Command 都在双引号字符串中。你如何逃避双引号?

【问题讨论】:

    标签: powershell batch-file escaping


    【解决方案1】:

    嗯,这里你需要在双引号字符串中转义命令行中的"。根据我的测试,似乎唯一可行的是在带引号的参数中使用四双引号 """"

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

    那么你的命令行应该是:

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

    还有另一种使用 PowerShell 处理此问题的方法,假设您不想只是将这些命令放在一个文件中并以这种方式调用它:使用 -EncodedCommand。这使您可以对整个命令或脚本进行 base64 编码,并将其作为单个参数传递到命令行。

    这是你原来的命令:

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

    这是一个对其进行编码的脚本:

    $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 现在包含:

    KABnAGMAIABjADoAXAB0AGUAbQBwAFwAdABlAG0AcAAxAC4AdAB4AHQAKQAgAC0AcgBlAHAAbABhAGMAZQAgACcAIgAnACwAIAAnACIAIgAnACAAfAAgAE8AdQB0AC0ARgBpAGwAZQAgAC0AZQBuAGMAbwBkAGkAbgBnACAAVQBUAEYAOAAgAGMAOgBcAHQAZQBtAHAAXAB0AGUAbQBwADIALgB0AHgAdAA = P>

    所以你的新命令行可以是:

    powershell.exe -encodedCommand KABnAGMAIABjADoAXAB0AGUAbQBwAFwAdABlAG0AcAAxAC4AdAB4AHQAKQAgAC0AcgBlAHAAbABhAGMAZQAgACcAIgAnACwAIAAnACIAIgAnACAAfAAgAE8AdQB0AC0ARgBpAGwAZQAgAC0AZQBuAGMAbwBkAGkAbgBnACAAVQBUAEYAOAAgAGMAOgBcAHQAZQBtAHAAXAB0AGUAbQBwADIALgB0AHgAdAA=
    

    无需担心逃避任何事情。

    【讨论】:

    • 我讨厌我刚刚才知道这一点。你知道我花了多少时间双引号和四引号转义以及运行和重新运行批处理脚本以试图让一切正确正确吗?谢谢
    【解决方案2】:

    转义字符是 PowerShell 的重音。试试这个:

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

    【讨论】:

    • @ChrisGciso 这不起作用,因为虽然反引号是 powershell 中的转义字符,但您需要从命令提示符中转义 ",以便将其传递给 powershell。
    • @ChrisGciso 刚刚再次检查。你说的对。它适用于 cygwin shell 和其他 *nix shell。我所要做的就是在 cmd shell 中加双引号。
    猜你喜欢
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多