Skip to content

Instantly share code, notes, and snippets.

@MikeFal
Created July 26, 2016 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeFal/ea39152c9be26fa5a3da917d33267141 to your computer and use it in GitHub Desktop.
Save MikeFal/ea39152c9be26fa5a3da917d33267141 to your computer and use it in GitHub Desktop.
#backup your databases
#get a collection of databases
$dbs = Invoke-Sqlcmd -ServerInstance localhost -Database tempdb -Query "SELECT name FROM sys.databases WHERE database_id > 4"
#Get a formatted string for the datetime
$datestring = (Get-Date -Format 'yyyyMMddHHmm')
#loop through the databases
foreach($db in $dbs.name){
$dir = "C:\Backups\$db"
#does the backup directory exist? If not, create it
if(!(Test-Path $dir)){New-Item -ItemType Directory -path $dir}
#Get a nice name and backup your database to it
$filename = "$db-$datestring.bak"
$backup=Join-Path -Path $dir -ChildPath $filename
Backup-SqlDatabase -ServerInstance localhost -Database $db -BackupAction Database -BackupFile $backup
Invoke-Sqlcmd -ServerInstance localhost -Database tempdb -Query $sql -QueryTimeout 6000
#Delete old backups
Get-ChildItem $dir\*.bak| Where {$_.LastWriteTime -lt (Get-Date).AddMinutes(-1)}|Remove-Item
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment