Skip to content

Instantly share code, notes, and snippets.

@spy86
Created August 3, 2017 10:15
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 spy86/a4c73cb3421d9240277559c97412dae6 to your computer and use it in GitHub Desktop.
Save spy86/a4c73cb3421d9240277559c97412dae6 to your computer and use it in GitHub Desktop.
$limit = (Get-Date).AddDays(-14)
$path = "C:\Backup\MSSQL\"
# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum")
$sqlobject = new-object ("Microsoft.SqlServer.Management.Smo.Server") "Server-name"
write-host "Simple Powershell script to backup all user database in MS SQL Server"
$Databases = $sqlobject.Databases
$backuppath = "C:\Backup\MSSQL"
foreach ($Database in $Databases)
{
if($Database.Name -ne "tempdb" -and $Database.Name -ne "Master" -and $Database.Name -ne "Model" -and $Database.Name -ne "MSDB")
#To skip system databases
{
write-host ".... Backup in progress for " $Database.Name "...."
$dbname = $Database.Name
$dt = get-date -format MMddyyyy-HHmm
$dbBackup = new-object ("Microsoft.SqlServer.Management.Smo.Backup")
$dbBackup.Action = "Database" # For full database backup, can also use "Log" or "File"
$dbBackup.Database = $dbname
$dbBackup.Devices.AddDevice($backuppath + "\" + $dbname + "-" + $dt + ".bak", "File")
$dbBackup.SqlBackup($sqlobject)
}
}
write-host "...........Finished..........."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment