Skip to content

Instantly share code, notes, and snippets.

@paulallies
Created April 26, 2013 09:06
Show Gist options
  • Select an option

  • Save paulallies/5465917 to your computer and use it in GitHub Desktop.

Select an option

Save paulallies/5465917 to your computer and use it in GitHub Desktop.
Powershell script for backing up database
## <Script>
### <Author>
### Chad Miller
### </Author>
### <Description>
### Excerpt from SQL Server Powershell Extensions (sqlpsx)
### http://sqlpsx.codeplex.com
### Defines backup and restore functions
### </Description>
### <Usage>
### . ./LibrarySqlBackup.ps1
### $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") 'Z002\SQL2K8'
### invoke-sqlbackup 'Z002\SqlExpress' 'pubs' $($server.BackupDirectory + "\pubs.bak")
### invoke-sqlrestore 'Z002\SqlExpress' 'pubs' $($server.BackupDirectory + "\pubs.bak") -force
### </Usage>
### </Script>
$smoAssembly = [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
if (!($smoVersion))
{ Set-Variable -name SmoVersion -value $smoAssembly.GetName().Version.Major -Scope Global -Option Constant -Description "SQLPSX variable" }
[void][reflection.assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended')
#######################
function Invoke-SqlBackup
{
param($sqlserver=$(throw 'sqlserver required.'),$dbname=$(throw 'dbname required.'),$filepath=$(throw 'filepath required.')
,$action='Database', $description='',$name='',[switch]$force,[switch]$incremental,[switch]$copyOnly)
#action can be Database or Log
$server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $sqlserver
Write-Verbose "Invoke-SqlBackup $($server.Name) $dbname"
$backup = new-object ("Microsoft.SqlServer.Management.Smo.Backup")
$backupDevice = new-object ("Microsoft.SqlServer.Management.Smo.BackupDeviceItem") $filepath, 'File'
$backup.Action = $action
$backup.BackupSetDescription = $description
$backup.BackupSetName = $name
if (!$server.Databases.Contains("$dbname")) {throw 'Database $dbname does not exist on $($server.Name).'}
$backup.Database = $dbname
$backup.Devices.Add($backupDevice)
$backup.Initialize = $($force.IsPresent)
$backup.Incremental = $($incremental.IsPresent)
if ($copyOnly)
{ if ($server.Information.Version.Major -ge 9 -and $smoVersion -ge 10)
{ $backup.CopyOnly = $true }
else
{ throw 'CopyOnly is supported in SQL Server 2005(9.0) or higher with SMO version 10.0 or higher.' }
}
trap {
$ex = $_.Exception
Write-Output $ex.message
$ex = $ex.InnerException
while ($ex.InnerException)
{
Write-Output $ex.InnerException.message
$ex = $ex.InnerException
};
continue
}
$backup.SqlBackup($server)
if ($?)
{ Write-Host "$action backup of $dbname to $filepath complete." }
else
{ Write-Host "$action backup of $dbname to $filepath failed." }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment