gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:30:07 29 4
gpt4 key购买 nike

我正在尝试使用从 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.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=



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

powershell.exe -encodedCommand KABnAGMAIABjADoAXAB0AGUAbQBwAFwAdABlAG0AcAAxAC4AdAB4AHQAKQAgAC0AcgBlAHAAbABhAGMAZQAgACcAIgAnACwAIAAnACIAIgAnACAAfAAgAE8AdQB0AC0ARgBpAGwAZQAgAC0AZQBuAGMAbwBkAGkAbgBnACAAVQBUAEYAOAAgAGMAOgBcAHQAZQBtAHAAXAB0AGUAbQBwADIALgB0AHgAdAA=

无需担心逃避任何事情。

关于powershell - 如何从 .bat 文件中转义 PowerShell 双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31575784/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com