Created
August 3, 2017 10:15
-
-
Save spy86/a4c73cb3421d9240277559c97412dae6 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
$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