Created
March 9, 2018 15:23
-
-
Save samonzeweb/e989c4d68d39fbb3336942a773f323f1 to your computer and use it in GitHub Desktop.
Backup all SQL Server databases with PowerShell
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
# SQL Server parameters | |
$serverInstance = 'localhost' | |
# Backup parameters | |
$backupDirectory = 'C:\path\to\backup\dir' | |
$retentionDays = 10 | |
# Mail parameters | |
$mailFrom = '[email protected]' | |
$mailTo = '[email protected]' | |
$mailSubject ="[FAIL] SQL Server backup on $env:computername" | |
$smtpServer = '1.2.3.4' | |
# No more parameters, don't touch the code below this comment. | |
# (or you will die in agony) | |
try { | |
# Remove old backups | |
$dateLimit = (Get-Date).AddDays(-1 * $retentionDays) | |
Get-ChildItem $backupDirectory | | |
Where { $_.CreationTime -lt $dateLimit } | | |
Remove-Item | |
# Backup all databases | |
Get-SqlDatabase -ServerInstance $serverInstance | | |
Where { $_.Name -ne 'tempdb' } | | |
foreach{ | |
$backupFile = "$($_.NAME)_db_$(Get-Date -UFormat %Y%m%d%H%M).bak" | |
$backupFile = Join-Path $backupDirectory -ChildPath $backupFile | |
Backup-SqlDatabase -DatabaseObject $_ -CompressionOption On -BackupFile $backupFile | |
} | |
} catch { | |
$message = $_.Exception.GetType().FullName + "`n" + | |
$_.Exception.Message | |
Write-Host -Foreground Red -Background Black $message | |
Send-MailMessage -From $mailFrom ` | |
-To $mailTo ` | |
-Subject $mailSubject ` | |
-Body $message ` | |
-SmtpServer $smtpServer | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment