Decrypting Files in Batch Using PowerShell


This article goes over how to decrypt a bunch of files that are encrypted using the same pgp key using a PowerShell script.

When a file is encrypted using PGP encryption, and you want to decrypt that file, the usual workflow is to add the private key to your keyring using: gpg --import .\private.asc and then decrypting the file using gpg --output [your_unencrypted_filename] --decrypt [your_encrypted_filename] and supplying the passphrase when prompted.

However, if you have a bunch of files and need to do this, the above method is sub optimal and inconvenient. You don’t want to be providing a decrypted filename and running the above command for every file. Instead, you can use the PowerShell script I wrote below.

The script looks for all files in the sourceFolder ending with a .gpg extension and saves decrypted files to the destinationFolder with the same name except without the .gpg extension.

# Define source and destination folders
$sourceFolder = "C:\path\to\your\encrypted_files"
$destinationFolder = "$sourceFolder\decrypted"

# Ensure the destination folder exists
if (!(Test-Path -Path $destinationFolder)) {
    New-Item -ItemType Directory -Path $destinationFolder | Out-Null
}

# Loop through all .gpg files in the source folder
Get-ChildItem -Path $sourceFolder -Filter "*.gpg" | ForEach-Object {
    $inputFile = $_.FullName
    $outputFile = "$destinationFolder\$(($_.Name) -replace '\.gpg$', '')"

    # Decrypt using GPG (Assumes GPG is installed and configured)
    gpg --batch --yes --decrypt --output $outputFile $inputFile
}

Save this script with a .ps1 extension and run it using: .\<script-name>.ps1

Leave a Reply

Your email address will not be published. Required fields are marked *

4 − one =