Created
October 31, 2024 07:02
-
-
Save aKamrani/c0e0e4fdba6be55d340a443b374736c2 to your computer and use it in GitHub Desktop.
Automatic Backup MSSQL Database to S3 Storage / Minio - Powershell Windows
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
| $server = "127.0.0.1" | |
| $database = "MMSQL_EXAMPLE_DATABSE" | |
| $currentDate = Get-Date -Format "yyyy-MM-dd" | |
| $backupFilePath = "F:\Backups\EXAMPLE-Backup-$currentDate.bak" | |
| $logFilePath = "F:\Backup-Logs\EXAMPLE-Backup-Logs.txt" | |
| $daysToKeep = 10 | |
| $mcPath = "F:\mc.exe" | |
| $minioUrl = "https://storage.example.com" | |
| $accessKey = "ACCESS_KEY" | |
| $secretKey = "SECRET_KEY" | |
| $bucketName = "BUCKET_NAME" | |
| $sqlBackup = @" | |
| BACKUP DATABASE MMSQL_EXAMPLE_DATABSE | |
| TO DISK = '$backupFilePath' | |
| WITH COMPRESSION, FORMAT, INIT, SKIP, NOREWIND, NOUNLOAD, STATS = 10; | |
| "@ | |
| function Log-Message { | |
| param ( | |
| [string]$message | |
| ) | |
| $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" | |
| $formattedMessage = "$timestamp - $message" | |
| Add-Content -Path $logFilePath -Value $formattedMessage | |
| } | |
| # Do Backup | |
| try { | |
| Invoke-Sqlcmd -ServerInstance $server -Database $database -Query $sqlBackup -QueryTimeout 600 | |
| Log-Message "Backup completed successfully to $backupFilePath." | |
| } catch { | |
| Log-Message "An error occurred during the backup: $_" | |
| } | |
| # Remove backups older than specified days | |
| try { | |
| $thresholdDate = (Get-Date).AddDays(-$daysToKeep) | |
| $oldBackupFiles = Get-ChildItem -Path $backupDirectory -Filter "*.bak" | Where-Object { $_.LastWriteTime -lt $thresholdDate } | |
| foreach ($file in $oldBackupFiles) { | |
| Remove-Item $file.FullName -Force | |
| Log-Message "Removed backup file: $($file.FullName)" | |
| } | |
| Log-Message "Clean-up of old backups completed." | |
| } catch { | |
| Log-Message "An error occurred during cleanup: $_" | |
| } | |
| # Push backup file to minio backup storage | |
| [Environment]::SetEnvironmentVariable("MC_INSECURE", "1", [EnvironmentVariableTarget]::User) | |
| & $mcPath alias set backups-deltadev $minioUrl $accessKey $secretKey | |
| & $mcPath cp $filePath "backups-deltadev/$bucketName/" | |
| if ($LASTEXITCODE -eq 0) { | |
| Log-Message "Backup uploaded successfully to MinIO." | |
| } else { | |
| Log-Message "Failed to upload backup file to MinIO." | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Docker container MSSQL command tool:
dump:
restore: