2017-03-01 34 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