Blog |Follow Nick on Twitter| About

Recently I've needed to backup some sensitive files to online storage; my requirement was simple: work on local files and when they change encrypt. As I'm working on a windows machine that means powershell, I could schedule a task but I'm just manually running this as and when I need... I'm sure there's a better way, but this will do for now!

Before you start you need GPG4Win as this script is just a wrapper for the pgp2.exe. If you've not used GPG4Win before you will need a key, in GPG4win land they call this Creating an OpenPGP Certificate... do that and take note of the email address you choose, it's important for the script.

Next create encrypt_these_files.ps1 in the folder that you want to back up, with this content:

# Variables, change these.
$gpg_r = "[email protected]"
$gpg_prog = "${env:ProgramFiles(x86)}" + "\GNU\GnuPG\pub\gpg2.exe"
$destination = "C:\Users\nick\DropOneDriveBox\encrypted\"

# simple gpg wrapper
function gpg_me {
  $in_file = $args[0]
  $out_file = $args[1]
  #Write-Host $in_file " | " $out_file
  & $gpg_prog --yes -e -r $gpg_r -o $out_file $in_file

# Loop thru current directory.
$items = Get-ChildItem -Path ".\"
foreach ($item in $items)
      # if the item is NOT a directory, then process it.
      if ($item.Attributes -ne "Directory") {
        $thepath =  $destination + $item.Name + ".gpg"
          If (Test-Path $thepath){
            # // File exists
            $ThisDate = $item.LastWriteTime
            $OtherDate = (Get-ChildItem -Path $thepath).LastWriteTime
            #Write-Host $item.Name " - This:" $ThisDate "Other:" $OtherDate
            If ( $ThisDate -gt $OtherDate) {
              Write-Host $item.Name "Needs updating.."
              gpg_me $item.Name $thepath
            # // File does not exist
            Write-Host "Encrypting New File "  $item.Name
            gpg_me $item.Name $thepath


At the top of the file, change the $gpg_r = "[email protected]" to your email address (used in the OpenPGP Certificate) and change $destination = "C:\Users\nick\DropOneDriveBox\encrypted\" to whatever folder you want.

If you've not run any powershell scripts then don't forget to set your execution policy before you execute the script .\encrypt_these_files.ps1 .



Nick Bettison ©