2017-03-01 35 views
0

我試圖從Powershell腳本調用gpg2。我需要使用嵌入式引號傳遞參數,但是當我直接從echoargs或可執行文件查看結果時,會遇到一些非常奇怪的行爲。Powershell:嵌入雙引號的gpg命令參數

$Passphrase = "PassphraseWith!$#" #don't worry, real passphrase not hardcoded! 
$Filename = "\\UNC\path\with\a space\mydoc.pdf.pgp" 
$EncyptedFile = $Filename -replace "\\", "/" 
$DecryptedFile = $EncyptedFile -replace ".pgp" , "" 

$args = "--batch", "--yes", "--passphrase `"`"$PGPPassphrase`"`"", "-o `"`"$DecryptedFile`"`"", "-d `"`"$EncyptedFile`"`"" 
& echoargs $args 
& gpg2 $args 

GPG要求我使用雙引號的密碼,因爲它有符號和由於空間的路徑(證實,當時我直接從命令提示符下運行樣品單個命令這工作)。此外,gpg希望使用正斜槓的UNC路徑(也證實了這一點)。

正如你所看到的,我正在嘗試用成對的轉義雙引號包裝密碼和文件路徑,因爲echoargs似乎表明外部引號正在被剝離。以下是我從echoargs得到:

Arg 0 is <--batch> 
Arg 1 is <--yes> 
Arg 2 is <--passphrase "PassphraseWith!$#"> 
Arg 3 is <-o "//UNC/path/with/a space/mydoc.pdf"> 
Arg 4 is <-d "//UNC/path/with/a space/mydoc.pdf.pgp"> 

Command line: 
"C:\Program Files (x86)\PowerShell Community Extensions\Pscx3\PSCX\Apps\EchoArgs.exe" --batch --yes "--pass 
phrase ""PassphraseWith!$#""" "-o ""//UNC/path/with/a space/mydoc.pdf""" "-d ""//UNC/path/with/a space/mydo 
c.pdf.pgp""" 

然而,gpg2給出以下結果(無論是從ISE或PS直接運行):

gpg2.exe : gpg: invalid option "--passphrase "PassphraseWith!$#""

如果我嘗試& gpg2 "$args"到數組轉換爲一個字符串,然後我得到以下類似的結果:

gpg2.exe : gpg: invalid option "--batch --yes --passphrase "PassphraseWith!$#"

在這一個任何想法?

+0

這會是一個荒謬的答案,但如果你真的在你的密碼有標誌的錢,你必須使用單引號... – Cole9350

+0

@ Cole9350我得到相同的結果,即使我從pw中取出符號,但是,在第1行的最初聲明中,$並跟隨字母數字將需要單引號 – cmcapellan

+0

'$ {Not $ args,因爲$ args是自動變量} =「 - 批處理「,」 - 「,」--passphrase「,」'「$ PGPPassphrase'」「,」-o「,」'「$ DecryptedFile'」「,」-d「,」'「$ EncyptedFile ' 「」; echoargs'$ {不是參數,因爲$參數是自動變量}'' – PetSerAl

回答

0

@ PetSerAl的解決方案:您需要來標記標誌/參數和它的價值,所以拆分到陣列中的兩個元素:

"--passphrase", "`"$Passphrase`"" 

不合併爲:

"--passphrase `"`"$Passphrase`"`"" 

注意使用反引號的常規PowerShell轉義引號在這裏工作正常。下面 完整的示例:

$Passphrase = "PassphraseWith!$#" #don't worry, real passphrase not hardcoded! 
$Filename = "\\UNC\path\with\a space\mydoc.pdf.pgp" 
$EncyptedFile = $Filename -replace "\\", "/" 
$DecryptedFile = $EncyptedFile -replace ".pgp" , "" 

$params = "--batch", "--quiet", "--yes", "--passphrase", "`"$Passphrase`"", "-o", "`"$DecryptedFile`"", "-d", "`"$EncyptedFile`"" 
& echoargs $params 
& gpg2 $params 
+0

@PetSerAl你是對的,謝謝指出。固定! – cmcapellan