Skip to content

Instantly share code, notes, and snippets.

@askvictor
Last active March 2, 2017 04:05
Show Gist options
  • Save askvictor/8b601ca8e6151874770a5ee7c0263080 to your computer and use it in GitHub Desktop.
Save askvictor/8b601ca8e6151874770a5ee7c0263080 to your computer and use it in GitHub Desktop.
Upload a file to Google Drive, and verify that it succeeded. Useful for backups.
# first use setup: run:
# gdrive-windows-x64.exe --config C:\programdata\GDrive about
# in order to setup auth token
# usage: backup-to-drive.ps1 -file backup_file [-delete_file] [-folder_id FOLDER_ID]
# -delete-file switch will delete the local copy once uploaded and verified
# -folder_id FOLDER_ID will upload to a specific folder on Google Drive (specify the ID from the URL of the folder)
# -email_server, -email_from and -email_to can be specified for notifications, or hard-code them here.
# if backup_file is a folder, then it will upload all items within that folder (and delete all of them if specified)
param (
[Parameter(Mandatory=$true)][string]$file,
[switch]$delete_file,
[string]$folder_id = $none,
[string]$email_server = "smtp.my.domain",
[string]$email_from = "server@my.domain",
[string]$email_to = "notifications@my.domain"
)
function send-error-email {
param( [string]$message )
Send-MailMessage -from $email_from -to $email_to -Subject "Error uploading backup on $env:computername" -body "There was an error: $message" -SmtpServer $email_server
}
try {
$files = Get-ChildItem $file
foreach ($file_obj in $files) {
$file_id = ""
if ($folder_id) {
$file_id = .\gdrive-windows-x64.exe --config C:\programdata\GDrive upload --no-progress -p $folder_id $file_obj.FullName | select-string -pattern "Uploaded ([^ ]*)" | % {$_.Matches.Groups[1].Value}
} else {
$file_id = .\gdrive-windows-x64.exe --config C:\programdata\GDrive upload --no-progress $file_obj.FullName | select-string -pattern "Uploaded ([^ ]*)" | % {$_.Matches.Groups[1].Value}
}
$remote_md5 = .\gdrive-windows-x64.exe --config C:\programdata\GDrive info $file_id | select-string -pattern "Md5sum: ([^ ]*)" | % {$_.Matches.Groups[1].Value}
$local_md5 = (Get-FileHash $file_obj.FullName -algorithm md5).Hash
if (-not (test-path variable:remote_md5) -or $remote_md5 -eq $none -or $local_md5 -eq $none -or $remote_md5 -ne $local_md5) {
send-error-email $file_obj.FullName
} else {
if ($delete_file) { #delete the file if switch was specified
Remove-Item $file_obj.FullName
}
}
}
} catch {
send-error-email $_.Exception.Message
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment