Created
July 26, 2016 19:36
-
-
Save MikeFal/ea39152c9be26fa5a3da917d33267141 to your computer and use it in GitHub Desktop.
This file contains 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
#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