Batch Script GPG Decryption
I am trying to write a batch file to decrypt a folder from files .gpg
all encrypted with the same public key. This is what I have so far:
@ECHO off
SET outbound=C:\encrypted files
SET olddir=%CD%
SET password=correcthorsebatterystaple
CD /d %outbound%
DIR *.gpg /B > tmp.txt
FOR /F "tokens=*" %%F IN (tmp.txt) DO (
ECHO %%F > tmplen.txt
FOR %%L IN (tmplen.txt) DO (SET namelen=%%~zL)
DEL tmplen.txt
gpg --output %%F:~0, namelen-4 --batch --yes --passphrase %password% --decrypt %%F)
DEL tmp.txt
CD /d %olddir%
Currently it just prints
usage: gpg [options] [filename]
This is my first time trying to write a Batch script, so I am pretty sure this is something simple.
source to share
The following should work:
@ECHO off
SET password=correcthorsebatterystaple
PUSHD "C:\encrypted files"
FOR /F "tokens=*" %%F IN ('DIR *.gpg /B') DO (
gpg --output %%~nF --batch --yes --passphrase %password% --decrypt %%F)
POPD
Explanation:
-
PUSHD
andPOPD
are used for temporary maneuver to another directory; - there is no temporary text file needed to store the output
DIR
, because it isFOR
also capable of parsing the output of a command (the set is internallyIN ()
enclosed in''
, so it is interpreted as a command, not a file specification.); - to truncate the file extension (which you want to do with the second temp file and the inner loop
FOR
, at least according to my interpretation), you just need to specify a modifier~n
, in our situation%%~nF
; your method doesn't work because:- you cannot do inline math calculations as you tried
namelen-4
(you will need to use an intermediate variable together withSET /A
for arithmetic operations, and also deferred expansion should have been active then); - type substring expansion
:~0,8
does not work with variablesFOR
(you need an intermediate variable for this, and again deferred expansion should be active then);
- you cannot do inline math calculations as you tried
Addition
If the script has problems with spaces in the input filenames, you may need to swap the command line gpg
with this:
gpg --output "%%~nF" --batch --yes --passphrase %password% --decrypt "%%~F"
Modifiers ~
remove potential surrounding double quotes, so "%%~nF"
they "%%~F"
always enclose the filename with double quotes. Note that it "%%F"
can inadvertently result in double quotes ...
source to share