簡體   English   中英

如何從 .bat 文件中轉義 PowerShell 雙引號

[英]How to escape PowerShell double quotes from a .bat file

我正在嘗試使用此 PowerShell 命令將文件(temp1.txt)中的所有雙引號替換為兩個雙引號,該命令從 Windows 7 中的 bat 文件運行:

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

我不斷收到錯誤:

'Out-File' 未被識別為內部或外部命令。

當我更改命令以將字母“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=

無需擔心逃避任何事情。

這是一個令人討厭的答案。 使用 ascii 代碼代替雙引號,即 34,並避免引用問題。 雙引號是一個特殊的 cmd.exe 字符,pipe 也是如此。

powershell "(gc temp1.txt) -replace [char]34,([char]34+[char]34) | set-content temp1.txt"

轉義字符是 PowerShell 的重音符號。 試試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM