In this guide, you will learn how to encrypt and decrypt files on a Windows computer with the help of PowerShell and PGP (Pretty Good Privacy).

Adam Bertram

Adam Bertram is a 20-year IT veteran, Microsoft MVP, blogger, and trainer. Adam is the founder of the e-learning tech screencast platform TechSnips. Catch up on Adam’s articles at adamtheautomator.com, or follow TechSnips on Twitter at @techsnips_io.

File encryption is commonplace these days. You can encrypt files in many ways with a lot of different tools. One way to do this is through an open-source encryption system called Pretty Good Privacy. PGP has been around a long time, and we can encrypt just about any form of data by using it. For now, we’re going to focus on encryption files using PGP and PowerShell.

To encrypt and decrypt files on Windows with PGP, we must download the GNU Privacy Guard for Windows utility. This free, open-source utility uses the OpenPGP Standard to bring PGP to Windows. We first need to download and install this.

We could go out to the website and do this manually, but we’re using PowerShell! Let’s stick to the command line. We could also figure out how to build a PowerShell tool around GnuPG for Windows ourselves, but why do that when a community module already exists?

Let’s save some time; downloading a PowerShell module from GitHub will expedite this process dramatically. To do that, I’ll reach out to GitHub and download a module called GnuPG and place it in a module path on my system.

Once I download the module, I can see I’ve got a few commands available to me.

Commands in the GnuPG PowerShell module

Commands in the GnuPG PowerShell module

One of those commands is Install-GnuPG. Let’s run that and see what happens.

This command went out to the GnuPG website, downloaded the installer, and then silently installed it. That saved some time!

Next, I need to encrypt a bunch of important files in a folder with a password only a few other people and I know. To do that, I can use the Add-Encryption command that comes with this module by simply using the Add-Encryption command specifying the folder of files I’d like to encrypt as well as the password I’d like use to secure them.

You can see below that I have a folder with a single file in it. I’m using the Add-Encryption command, which calls the GnuPG utility under the covers to encrypt this file using the password I’m specifying. It returns a GPG file that is the contents of the file encrypted. At this point, I could just remove the original file if I desired.

Encrypting a file with PowerShell

Encrypting a file with PowerShell

Now that the file is encrypted in the GPG file, it can’t be read unless decrypted. This GnuPG utility processes the file by first decrypting it, then creating a file of the same name with the unencrypted contents.

You can see below that I’m using the Remove-Encryption command and passing the path of the folder and the secret. The GnuPG utility is creating a keyring if it doesn’t exist yet, decrypting the file, and the Remove-Encryption function is returning the path to the folder that I passed in.

We can now read that original file like normal!

By using the GnuPG utility along with the GnuPG PowerShell module, we can quickly create a handy little tool that can apply encryption to any number of files on the fly. This is an excellent solution for times when you don’t need anything fancy but need a quick way to encrypt files securely with a password.

Join the 4sysops PowerShell group!

6+

Users who have LIKED this post:

  • avatar
  • avatar
  • avatar
Share
15 Comments
  1. Indra A 1 year ago

    Sir,

    I have used your code for encryption and decryption for PGP files in file server. But when I am decrypting, it is asking for password even though Im using the same code

    param
    (
    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    #[ValidateScript({ Test-Path -Path $_ -PathType Container })]
    [string]$FolderPath,

    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [string]$Password,

    [Parameter()]
    [ValidateNotNullOrEmpty()]
    [string]$GpgPath = 'C:\Program Files (x86)\GnuPG\bin\gpg.exe'
    )
    process
    {
    try
    {
    Get-ChildItem -Path $FolderPath -Filter '*.pgp' | foreach {
    $decryptFilePath = $_.FullName.TrimEnd('.pgp')
    Write-Verbose -Message "Decrypting [$($_.FullName)] to [$($decryptFilePath)]"
    $startProcParams = @{
    'FilePath' = $GpgPath
    'ArgumentList' = "--batch --yes --passphrase $Password -o $decryptFilePath -d $($_.FullName)"
    'Wait' = $true
    'NoNewWindow' = $true
    }
    $null = Start-Process @startProcParams
    }
    Get-ChildItem -Path $FolderPath | where {$_.Extension -ne 'pgp'}
    }
    catch
    {
    Write-Error $_.Exception.Message
    }
    }

    But it is opening a window pinquery -qt

    asking for passphrase

     

    3+

  2. Adam 8 months ago

    Keep getting error:

    Add-Encryption : This command cannot be run due to the error: The system cannot find the file specified.
    At line:1 char:1
    + Add-Encryption -FolderPath c:\pgptest -Password dellwatts1
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Add-Encryption

    At my wits end. There are files in that directory. I've reached the end of google. I've tried single and double quotes. Tried run as admin. Any help would be much appreciated thank you. And thank you for the great tutorial. I wouldn't even get this far without it.

    0

    • Adam 7 months ago

      nevermind got it. installation issue.

      0

      • Ravit Kumar 7 months ago

        Hey Adam,

        I am facing the same issue here with powershell unable to find the file specified.

        How did resolve this?

        0

        • Luc Fullenwarth 7 months ago

          @ravit

          You must first execute the 4 lines at the beginning of this article in order to install the function.

          0

  3. New 6 months ago

    Has anyone been able to get Remove-Encryption to actual work via Powershell?

    Error:

    Remove-Encryption : Cannot validate argument on parameter 'FolderPath'. The " Test-Path -Path $_ -PathType Container " validation script for the argument with value
    "\\NDH2CPRW2FSR001\ftp\Tallahassee\Hold\*gpg" did not return a result of True. Determine why the validation script failed, and then try the command again.

     

    0

    • Luc Fullenwarth 6 months ago

      @New
      That's because you used a wildcard.
      If you have several folders to uncypher, use the Foreach statement.
      For example:

      0

      • John C Brenner 2 months ago

        Nope same error even with your script block.  

        I have a working script that functions interactively but not as a scheduled task 

        $list = gci '\\someuncpath\'

        foreach ($file in $list.name)
        {$out = $File -replace ".pgp", ""

        & gpg2 --batch --passphrase "secret" --armor --output $out --decrypt $file 2> $null}

        0

  4. Crow 4 months ago

    Running this script on A LOT of files and ran into a rather strange issue. the files are [filename].zip.gpg. When I run this script, it renames the files to .zi, removing the P in .zip.

    0

    • Swapnil Kambli 4 months ago

      Hi Crow,

      Script just has below trim code to remove the gpg extension. 
      $_.FullName.TrimEnd('.gpg')

      Is this behaviour just specific to zip files?
      Is the decryption-renaming working fine for other files?

      0

  5. Martin 3 months ago

    This method fails if the filename contains any spaces... 🙁

    1+

    Users who have LIKED this comment:

    • avatar
    • Swapnil Kambli 3 months ago

      Please use below block for Remove-Encryption function within gnupg module for a workaround on space in the filename error.

      1+

      • Swapnil Kambli 3 months ago

        Also, don't forget to unload the 'gnupg' module using remove-module and re-load the module using import-module cmdlets one you make above changes.

        0

  6. Nemo 1 month ago

    As mentioned above, the "Remove-Encryption" function was converting my ".zip.gpg" files to ".zi" using the "TrimEnd(".gpg") method. To get around it, I changed the code to use the "Substring" method instead and now it correctly converts my ".zip.gpg" files to ".zip". Here's my code snippet :

    0

  7. Frank 2 days ago

    If you cannot get it to work you nee to use "Install-GnuPG -DownloadFolderPath 'C:\'" which will get you gpg4win-2.2.5.exe, gpg4win-3.1.10.exe will not work.

    0

Leave a reply

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

*

© 4sysops 2006 - 2019

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account