|
| 1 | +function Backup-FilesToS3 { |
| 2 | + <# |
| 3 | + .SYNOPSIS |
| 4 | + Creates backups, uploads them to AWS S3, and retains some locally |
| 5 | +
|
| 6 | + .DESCRIPTION |
| 7 | + This powershell module is designed to make creation of backups simple |
| 8 | + and easy and to allow for easy uploading of those backups to S3 for |
| 9 | + long-term archival and disaster recovery. |
| 10 | + |
| 11 | + Author: Nathan Przybyszewski <github.com/shibz> |
| 12 | + License: MIT License |
| 13 | + |
| 14 | + Before using this script, you need to create your backup_settings.txt |
| 15 | + file using the included template. You also should run the following |
| 16 | + command as administrator to set up logging: |
| 17 | + |
| 18 | + New-EventLog -LogName Application -Source "YourBackupSourceName" |
| 19 | + |
| 20 | + Replace YourBackupSourceName with the actual setting you configured |
| 21 | + in backup_settings.txt |
| 22 | + |
| 23 | + .PARAMETER name |
| 24 | + Name for the backups. Date/time will be appended. |
| 25 | + |
| 26 | + .PARAMETER source |
| 27 | + Location to backup. |
| 28 | + |
| 29 | + .PARAMETER cfgFile |
| 30 | + Configuration file that will be used to deremine where to backup to. |
| 31 | + |
| 32 | + .EXAMPLE |
| 33 | + Backup files locally and to S3 as specified by configuration file. |
| 34 | + |
| 35 | + Backup-FilesToS3 "documents" "C:\Users\Administrator\My Documents\*" "C:\backups\backup_settings.txt" |
| 36 | + #> |
| 37 | + Param( |
| 38 | + [Parameter(Mandatory=$true)][string]$name, |
| 39 | + [Parameter(Mandatory=$true)][string]$source, |
| 40 | + [Parameter(Mandatory=$true)][string]$cfgFile |
| 41 | + ) |
| 42 | + |
| 43 | + # Ensure 7-zip is installed and the necessary backup settings file exists |
| 44 | + if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"} |
| 45 | + if (-not (test-path "$cfgFile")) {throw "$cfgFile was not found. Copy backup_settings.template.txt and configure as desired. Location of your configuration must be passed to cmdlet as a parameter."} |
| 46 | + |
| 47 | + # Fetch backup config file content and populate $backupSettings with values |
| 48 | + Get-Content "$cfgFile" | foreach-object -begin {$backupSettings=@{}} -process { $k = [regex]::split($_,'='); if(($k[0].CompareTo("") -ne 0) -and ($k[0].StartsWith("[") -ne $True) -and ($k[0].StartsWith("#") -ne $True)) { $backupSettings.Add($k[0], $k[1]) } } |
| 49 | + |
| 50 | + # Set the logging-related variables |
| 51 | + $script:logSource = $backupSettings.LogSource |
| 52 | + $script:debug = $backupSettings.Debug |
| 53 | + |
| 54 | + # Set the AWS credentials |
| 55 | + Set-AWSCredential -AccessKey "$($backupSettings.AccessKey)" -SecretKey "$($backupSettings.SecretKey)" |
| 56 | + Set-DefaultAWSRegion -Region "$($backupSettings.S3Region)" |
| 57 | + |
| 58 | + $now = Get-Date |
| 59 | + $timestamp = Get-Date -Date $now -format yyyy-MM-dd_H-mm-ss |
| 60 | + $backupDir = "$($backupSettings.LocalBackupDir)\$name" |
| 61 | + $backupName = "$backupDir\$name`_$timestamp.bak.7z" |
| 62 | + $cloudUpload = $backupSettings.CloudUpload -like "true" |
| 63 | + Write-BackupLog "Beginning backup for $name to $backupName.`r`nWill attempt to save:`r`n$source" 110 |
| 64 | + |
| 65 | + if ($source -is [array]) { |
| 66 | + $szoutput = Zip-Files "$backupName" @source |
| 67 | + } else { |
| 68 | + $szoutput = Zip-Files "$backupName" $source |
| 69 | + } |
| 70 | + Write-BackupDebug "7Zip completed. Output was:`r`n$szoutput" 120 |
| 71 | + |
| 72 | + if ($cloudUpload) { |
| 73 | + $uploadlog = Upload-Backup $backupName $backupSettings.S3Bucket "$name.7z" $now |
| 74 | + } else { |
| 75 | + $uploadlog = "Backup was not uploaded to S3" |
| 76 | + } |
| 77 | + |
| 78 | + $backupMax = $now.AddDays([int]$backupSettings.LocalBackupRetention * -1) |
| 79 | + $oldfiles = Get-ChildItem $backupdir -recurse -include "$backupname_*.bak.7z" | Where-Object { $_.CreationTime -le $backupMax } |
| 80 | + if ($oldfiles) { |
| 81 | + $measurement = $oldfiles | Measure-Object -property length -sum |
| 82 | + $pruneCount = $measurement.Count |
| 83 | + $pruneSize = [math]::Round($measurement.Sum / 1KB) |
| 84 | + $prunelog = "Pruning old archives.`r`nWill attempt to prune $pruneCount files totalling $pruneSize KB:`r`n$oldfiles`r`n$uploadlog" |
| 85 | + Write-BackupDebug $prunelog 140 |
| 86 | + Remove-Item $oldfiles |
| 87 | + } else { |
| 88 | + $prunelog = "No files found for pruning" |
| 89 | + } |
| 90 | + |
| 91 | + Write-BackupLog "Backup for $name to $backupName is complete!`r`nBackup target was: $source`r`n`r`n7Zip output was:`r`n$szoutput`r`n$prunelog`r`n$backuplog" 150 |
| 92 | +} |
| 93 | + |
| 94 | +# Create an encrypted 7-zip archive |
| 95 | +function Zip-Files { |
| 96 | + "$env:ProgramFiles\7-Zip\7z.exe" a -mx7 -mhe -mmt -p"$($backupSettings.EncryptionPassword)" $args |
| 97 | +} |
| 98 | + |
| 99 | +# Write to event log, only if debug mode is enabled |
| 100 | +function Write-BackupDebug($message, $id) { |
| 101 | + if ($script:debug) { |
| 102 | + Write-EventLog -LogName Application -Source $script:logSource -EventId "$id" -Message "$message" |
| 103 | + echo $message |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +# Write informational message to event log |
| 108 | +function Write-BackupLog($message, $id) { |
| 109 | + Write-EventLog -LogName Application -Source $script:logSource -EventId "$id" -Message "$message" |
| 110 | + echo $message |
| 111 | +} |
| 112 | + |
| 113 | +# Write error message to event log |
| 114 | +function Write-BackupError($message, $id) { |
| 115 | + Write-EventLog -LogName Application -Source $script:logSource -EventId "$id" -Message "$message" -EntryType Error |
| 116 | + echo $message |
| 117 | +} |
| 118 | + |
| 119 | +# Upload the given file to S3 |
| 120 | +function Upload-Backup($file, $bucket, $key, $date) { |
| 121 | + $prefixDate = Get-Date -Date $date -format yyyy-MM-dd/HH-mm-ss |
| 122 | + $archiveKey = "$prefixDate`_$key" |
| 123 | + $backupLog = "" |
| 124 | + |
| 125 | + Write-BackupDebug "Attempting to upload $file to s3://$bucket/$archiveKey" 135 |
| 126 | + try { |
| 127 | + Write-S3Object -BucketName $bucket -File $file -Key $archiveKey |
| 128 | + $backupLog = "Uploaded $file to s3://$bucket/$archiveKey" |
| 129 | + } catch { |
| 130 | + $errormsg = $_.Exception.Message |
| 131 | + Write-BackupError "Error uploading to S3! Error was:`r`n$errormsg" 235 |
| 132 | + } |
| 133 | + Write-BackupDebug $backupLog 130 |
| 134 | + |
| 135 | + return $backupLog |
| 136 | +} |
| 137 | + |
| 138 | +Export-ModuleMember -Function Backup-FilesToS3 |
0 commit comments