Powershell: gpg command parameters with embedded double quotes - powershell

I'm trying to call gpg2 from a Powershell script. I need to pass parameters with embedded quotes but I get some very odd behavior when I look at the results from echoargs or the executable directly.
$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 requires me to use double quotes for the passphrase because it has symbols and for the paths because of a space (confirmed this works when I run a sample single command directly from command prompt). Also, gpg wants UNC paths with forward slashes (confirmed this works too).
As you can see I am trying to wrap the passphrase and file paths with paired escaped double quotes because echoargs seems to indicate the outer quotes are being stripped off. Here is what i get from 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"""
However, gpg2 gives the following result (whether run from ISE or PS directly):
gpg2.exe : gpg: invalid option "--passphrase "PassphraseWith!$#""
If I try & gpg2 "$args" to convert the array to a string then I get the following similar result:
gpg2.exe : gpg: invalid option "--batch --yes --passphrase "PassphraseWith!$#"
Any ideas on this one?

#PetSerAl's solution: You need to tokenize the flag/parameter and its value, so split out into two elements in the array:
"--passphrase", "`"$Passphrase`""
not combined as:
"--passphrase `"`"$Passphrase`"`""
Note that regular Powershell escaping quotes using backticks works fine here.
Full example below:
$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

Related

Adding variable to text string and adding new line in powershell

I have the following code
$scriptpath = "C:\Test"
$scriptname = "mount.bat"
$myimage = Read-Host 'Enter the file name of your image'
if (Test-Path $scriptpath\$scriptname) {
Remove-Item $scriptpath\$scriptname
}
Add-Content $scriptpath\$scriptname ':Loop 'n "C:\Program
Files\file.exe" -f \\host\"Shared Folders"\$myimage -m V: `n if not
%errorlevel% equal 0 goto :Loop'
I can't get powershell to output the variable correctly in the output batch file it just says "$myimage" and not the file name. I have tried using the break ` ' symbols but no luck. I also cannot get powershell to export onto a separate line. If anyone could help that would be great.
Since you're using (a) variable references ($myimage) and (b) escape sequences such as `n (to represent a newline) in your string, you must use double quotes to get the expected result.
(Single-quoted strings treat their contents literally - no interpolation takes place.[1])
Furthermore, since your string has embedded double quotes, they must be escaped as `"
Here's a fixed version; note that I've used actual line breaks for readability (rather than `n escape sequences in a single-line string):
$myImage = 'test.png'
":Loop
`"C:\ProgramFiles\file.exe`" -f \\host\`"Shared Folders`"\$myimage -m V:
if not %errorlevel% equal 0 goto :Loop"
[1] The only interpretation that takes place is to recognize escape sequence '' as an embedded '.

How to correctly escape spaces and backslashes in command line arguments?

I had some issues passing an array of strings to a command in PowerShell, so I'm debugging my script. I'm using the EchoArgs.exe program found in the PowerShell Community Extension Project (PSCX).
If I execute this script:
Import-Module Pscx
cls
$thisOne = 'this_one\';
$secondOne = 'second one\';
$lastOne = 'last_one'
$args = $thisOne `
, "the $secondOne" `
, "the_$lastOne"
EchoArgs $args
I get this result:
Arg 0 is <this_one\>
Arg 1 is <the second one" the_last_one>
Command line:
"C:\Program Files (x86)\PowerShell Community Extensions\Pscx3\Pscx\Apps\EchoArgs.exe" this_one\ "the second one\" the_last_one
It seems that if a string contains spaces, the last backslash escapes the double quote. In fact all seems working if I escape only that backslash:
Import-Module Pscx
cls
$thisOne = 'this_one\';
$secondOne = 'second one\\';
$lastOne = 'last_one'
$args = $thisOne `
, "the $secondOne" `
, "the_$lastOne"
EchoArgs $args
with this result:
Arg 0 is <this_one\>
Arg 1 is <the second one\>
Arg 2 is <the_last_one>
Command line:
"C:\Program Files (x86)\PowerShell Community Extensions\Pscx3\Pscx\Apps\EchoArgs.exe" this_one\ "the second one\\" the_last_one
Is there a "smart" way in PowerShell (i.e. a cmdlet) to escape any string in order to avoid such issues?
Try using Start-Process instead. It has an $Arguments parameter that would suit this better.
See here: PowerShell - Start-Process and Cmdline Switches

Word separator in powershell

I need to open a folder on a FTP server. The folder name [DAILY Files Folder] has SPACE between the words. If I try it in CMD I can use double quotes and it works. but in power shell I need the double quotes to run the actual command! does anyone know how can I add the space in my folder name without using double quotes?
$cmd = #(
"cd /DAILY Files Folder",
"put $file",
"bye"
)
[String]($cmd | & $program -pw $pass "$user#$hst" 2>&1)
Escape nested double quotes with backticks (`):
$cmd = #(
"cd `"/DAILY Files Folder`"",
"put $file",
"bye"
)
[String]($cmd | & $program -pw $pass "$user#$hst" 2>&1)
or use single quotes as the outer quotes if you don't use variables inside the string:
$cmd = #(
'cd "/DAILY Files Folder"',
"put $file",
'bye'
)
[String]($cmd | & $program -pw $pass "$user#$hst" 2>&1)
you can use the back tick character (`) to escape each space:
DAILY` Files` Folder

Piping from a variable instead of file in Powershell

Is ther any way in Powershell to pipe in from an virable instead of a file?
There are commands that I need to pipe into another command, right now that is done by first creating a file with the additional commands, and then piping that file into the original command. Code looks somehting like this now:
$val = "*some command*" + "`r`n" + "*some command*" + "`r`n" + "*some command*"
New-Item -name Commands.txt -type "file" -value $val
$command = #'
db2cmd.exe /C '*custom db2 command* < \Commands.txt > \Output.xml'
'#
Invoke-Expression -Command:$command
So instead of creating that file, can I somehow just pipe in $val insatead of Commands.txt?
Try this
$val = #("*some command*1","*some command2*","*some command3*")
$val | % { db2cmd.exe /C $_ > \Output.xml }
You should be able to pipe in from $val provided you use Write-Output or its shorthand echo, but it may also be worth trying passing the commands directly on the command line. Try this (and if it doesn't work I can delete the answer):
PS C:\> filter db2cmd() { $_ | db2cmd.exe ($args -replace '(\\*)"','$1$1\"') }
PS C:\> $val = #"
>> *custom db2 command*
>> *some command*
>> *some command*
>> *some command*
>> "#
>>
PS C:\> db2cmd /C $val > \Output.xml
What happens here is that Windows executables receive their command line from a single string. If you run them from cmd.exe you cannot pass newlines in the argument string, but Powershell doesn't have that restriction so with many programs you can actually pass multiple lines as a single argument. I don't know db2cmd.exe so it might not work here.
The strange bit of string replacement is to handle any double quotes in the arguments: Powershell doesn't quote them and the quoting rules expected by most exe files are a bit bizarre.
The only limitation here would be that $val must not exceed about 32,600 characters and cannot contain nulls. Any other restrictions (such as whether non-ascii unicode characters work) would depend on the application.
Failing that:
echo $val | db2cmd.exe /C '*custom db2 command*' > \Output.xml
may work, or you can use it in combination with the filter I defined at the top:
echo $val | db2cmd /C '*custom db2 command*' > \Output.xml

Spaced paths, msbuild, and psake

Related question here.
This works properly for compiling an mvc3 application.
task Compile
{
$config = $script:siteConfig.config
exec { & "C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe" $webproject_path `
/p:Configuration=$config /p:WebProjectOutputDir="$publish_dir" `
/p:Outdir="$out_dir" /p:CleanWebProjectOutputDir=False `
/T:_WPPCopyWebApplication /T:ResolveReferences /verbosity:quiet /nologo }
}
All of those path variables are script properties. However, when spaces are introduced in those calculated paths (e.g. the project is moved from C:\Projects\ to C:\Users\ASDFG1\Documents\Visual Studio 2010\Projects) msbuild thinks there's multiple project files. This makes sense but I have to be missing something, getting a parsed variable into quotes shouldn't be this hard.
Variations tried
exec { Invoke-Expression "& C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe '$webproject_path' /p:Configuration=$config /p:WebProjectOutputDir='$publish_dir' /p:Outdir='$out_dir' /p:CleanWebProjectOutputDir=False /T:_WPPCopyWebApplication /T:ResolveReferences /verbosity:quiet /nologo" }
exec { C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe "`"$webproject_path`"" `
/p:Configuration=$config /p:WebProjectOutputDir="`"$publish_dir`"" `
/p:Outdir="`"$out_dir`"" /p:CleanWebProjectOutputDir=False `
/T:_WPPCopyWebApplication /T:ResolveReferences /verbosity:quiet /nologo }
Using EchoArgs.exe to reproduce the problem, we see that quotes are not being passed to the executable as desired:
PS> $publish_dir = 'C:\Users\Documents\Visual Studio 2010\Projects'
PS> ./echoargs /p:WebProjectOutputDir="$publish_dir"
Arg 0 is </p:WebProjectOutputDir=C:\Users\Documents\Visual Studio 2010\Projects>
PS> ./echoargs /p:WebProjectOutputDir="`"$publish_dir`""
Arg 0 is </p:WebProjectOutputDir=C:\Users\Documents\Visual>
Arg 1 is <Studio>
Arg 2 is <2010\Projects>
Using the backslash-escaping option from this answer, we can preserve the variable expansion and the enclosing quotes:
PS> ./echoargs /p:WebProjectOutputDir=\`"$publish_dir\`"
Arg 0 is </p:WebProjectOutputDir="C:\Users\Documents\Visual Studio 2010\Projects">
Here, the backticks tell PowerShell to treat the quote characters as literal values, and the backslash tells the call invocation to preserve the quotes.
Alternatively, we could stick with a single level of escaping by evaluating the full argument beforehand, instead of inlining the $publish_dir variable:
PS> $publishArg = '/p:WebProjectOutputDir=\"{0}\"' -f $publish_dir
PS> ./echoargs $publishArg
Arg 0 is </p:WebProjectOutputDir="C:\Users\Documents\Visual Studio 2010\Projects">