Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Azure4Arjun/0418d5bac8c87e2af9b2b53fe8c8b8c5 to your computer and use it in GitHub Desktop.
Save Azure4Arjun/0418d5bac8c87e2af9b2b53fe8c8b8c5 to your computer and use it in GitHub Desktop.
Backup all user and system databases except for TEMPDB. Compress all SQL backups to local disk using 7zip. Copy backups to multiple locations based on configurations. Get MD5 hash for multiple locations and roll back the copy if the hashes don't match.
Import-Module -Name SqlServer
# CONFIGURATIONS:
$locationA = "C:\temp\share1"
$locationB = "C:\temp\\share2"
$local = "C:\temp"
$SqlServerLocation = "SQLSERVER:\SQL\localhost\DEFAULT\Databases"
$retries = 5
Set-Location $SqlServerLocation
# backup all user and system databases except for TEMPDB
foreach ($database in (Get-ChildItem -force) | Where { $_.Name -ne 'tempdb'} )
{
$dbName = $database.Name
Backup-SqlDatabase -Database $dbName -BackupFile "$local\$dbName.bak"
}
# Compress all SQL backups to local disk using 7zip
dir "$local\*.bak" | ForEach-Object { & "7z.exe" a $_.BaseName $_.Name }
# copy backups to multiple locations based on configurations
# get MD5 hash for multiple locations and roll back the copy if the hashes don't match
$count=0
do{
Get-ChildItem "$local" -Filter *.7z | Foreach-Object {
start-transaction
copy-item $_.FullName -Destination $locationA
copy-item $_.FullName -Destination $locationB
Get-FileHash $locationA\$_ -Algorithm MD5 | select -ExpandProperty Hash > $locationA\$_.hash
Get-FileHash $locationB\$_ -Algorithm MD5 | select -ExpandProperty Hash > $locationB\$_.hash
$hashLocationA = Get-FileHash $locationA\$_ -Algorithm "MD5"
$hashLocationB = Get-FileHash $locationB\$_ -Algorithm "MD5"
If ($hashLocationA.HashString -ne $hashLocationB.HashString){
undo-transaction
}
else {
remove-item $_.FullName
complete-transaction
$success = $true
}
$count++
}
}until($count -eq $retries -or $success)
if(-not($success)){exit}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment