如何从.bat文件中转义PowerShell双引号

如何从.bat文件中转义PowerShell双引号,powershell,batch-file,escaping,Powershell,Batch File,Escaping,我正在尝试使用从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 co

我正在尝试使用从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的重重音。请尝试以下方法:

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

嗯,这里您需要在双引号字符串中转义命令行上的
”。根据我的测试,唯一有效的方法是在引号参数中使用四个双引号

powershell.exe-命令“echo”“X”“”
那么您的命令行应该是:

powershell-Command”(gc c:\temp\temp1.txt)-替换'''''''''.''和''''''.''输出文件-编码UTF8 c:\temp\temp2.txt“
使用PowerShell还有另一种处理方法,假设您不想将这些命令放在一个文件中并以这种方式调用它:使用
-EncodedCommand
。这样可以对整个命令或脚本进行base64编码,并将其作为单个参数传递到命令行

这是您最初的命令:

(gc c:\temp\temp1.txt)-替换“,”Out文件-编码UTF8 c:\temp\temp2.txt
下面是对其进行编码的脚本:

$c=@”
(gc c:\temp\temp1.txt)-替换“,”“”“| Out文件-编码UTF8 c:\temp\temp2.txt
"@
$b=[System.Text.Encoding]::Unicode.GetBytes($c)
$e=[System.Convert]::ToBase64String($b)
$e
现在包含:

这是一个很好的例子,它是一个很好的例子,它是一个很好的例子=

因此,您的新命令行可以是:

powershell.exe-编码命令kabNagmaiabjadoaxab0aguabqbwadabag0acaaxac4adab4ahqakqagac0acgagabhabhagmazqaccaacgacgacgacgacwacwac0argbPagwacqaggac0azaqbumabkagkabgac0acgac8adqb0agb0agbwaggacgacgacqaqaqaqaqaqaqaqaqaqaqaqaqaqaqaqaqaqaqaqaqaqaqaqaqa=

无需担心转义任何内容。

@ChrisGciso这不起作用,因为虽然backtick是powershell中的转义字符,但您需要从命令提示符转义
,以便将其传递给powershell。@ChrisGciso刚刚再次检查。你是对的。它适用于cygwin shell和其他*nix shell。我所要做的就是在cmd shell中使用双引号。我讨厌我只是刚刚了解到这一点。你知道我花了多少时间来转义双引号和四引号,运行并重新运行批处理脚本,试图让一切都正常吗?非常感谢。