Created
December 25, 2023 09:18
-
-
Save koss822/1578d2b060db11f215137e42a5e3235a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Add to task scheduler | |
# Start a program; Powershell.exe -ExecutionPolicy Bypass -File "backupvm.ps1" | |
# Define variables | |
$VMName = "VM Name" | |
$ExportPath = "C:\backups" | |
$RarFileName = "vm-name" | |
$RarFileNameWithDate = "$RarFileName-$(Get-Date -Format 'yyyyMMdd-HHmmss')" | |
$S3Bucket = "hyperv-backup-s3" | |
$SNSArn = "arn:aws:sns:eu-west-1:xxxx:Backup" | |
$daysToKeep = 90 | |
$currentDate = Get-Date | |
$WinRARExe = "C:\Program Files\WinRAR\rar.exe" | |
$RecoveryRecordSize = "5%" # Set the desired percentage for the recovery record | |
try { | |
# Export Hyper-V machine | |
Export-VM -Name "$VMName" -Path "$ExportPath" | |
# Change current working directory to export path | |
Set-Location -Path $ExportPath | |
# Compress with Rar | |
$WinRARCommand = "& '$WinRARExe' a -rr$RecoveryRecordSize '${RarFileNameWithDate}.rar' '$VMName'" | |
Invoke-Expression $WinRARCommand | |
# Upload to S3 Glacier | |
aws s3 cp "$ExportPath\${RarFileNameWithDate}.rar" "s3://$S3Bucket/${RarFileName}.rar" | |
# List files in S3 bucket | |
$S3FileList = aws s3 ls s3://$S3Bucket/ | |
# Send SNS notification for successful backup with file list | |
$SNSMessage = "Backup of $VMName completed successfully. File: $ZipFileName.`nFiles in S3 Bucket:`n$S3FileList" | |
aws sns publish --topic-arn $SNSArn --message "$SNSMessage" | |
# Get all zip files older than 90 days | |
$filesToDelete = Get-ChildItem -Path $ExportPath -Filter *.zip | Where-Object { $_.LastWriteTime -lt ($currentDate.AddDays(-$daysToKeep)) } | |
foreach ($file in $filesToDelete) { | |
Remove-Item $file.FullName -Force | |
Write-Host "Deleted: $($file.FullName)" | |
} | |
} | |
catch { | |
# Handle S3 upload failure | |
$ErrorMessage = $_.Exception.Message | |
Write-Host "S3 Upload Failed: $ErrorMessage" | |
# Send SNS notification for upload failure | |
aws sns publish --topic-arn $SNSArn --message "S3 Upload of $VMName failed. Error: $ErrorMessage" | |
} | |
finally { | |
# Clean up temporary files | |
Remove-Item "$ExportPath\$VMName" -Recurse -Force | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment