param ( [string] $Server, [string] $Database, [string] $BackupPath ) ## Path and name used to invoke script $CUR_SCRIPT = $myinvocation.InvocationName ## Load SMO assemblies [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")|out-null [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum")|out-null [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")|out-null $SMO = [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") ## Parse out the internal version number $SMOVer = $SMO.FullName.Split(",")[1].Split("=")[1].Split(".")[0] ## Load SMOExtended if not SQL Server 2005 (9) if ($SMOVer -ne 9) { [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMOExtended")|out-null } ## Check user input, prompt for each value not provided as parameters if(!$Server) { $Server = read-host "Enter Server Name" } if(!$Database) { $Database = read-host "Enter Database Name" } if(!$BackupPath) { $BackupPath = read-host "Enter Backup Path (optional)" } ## Return Help and exit if any required input is missing if(!$Server -or !$Database) { write-host "Usage: $CUR_SCRIPT options: string SQL Server Instance string Database Name string Backup Path (optional)" -f red exit } ## Function to raise error Function RaisError ([string]$ErrMsg){ write-host $ErrMsg -f red $error.clear() } ## Create server object $Srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $Server ## Get default backup path if not provided if (!$BackupPath) { $BackupPath = $Srv.BackupDirectory } ## Make sure backup path exists if ($BackupPath) { $BackupPath = [System.IO.Path]::Combine($BackupPath, $Database) [System.IO.Directory]::CreateDirectory($BackupPath) | out-null } else { RaisError "`tUnable to find a backup path" } ## Connect to database $DBase = $Srv.Databases[$Database] ## Create backup name $BkDate = Get-Date -Format yyyyMMddHHmmss $BkName = $Database + "_backup_$BkDate.bak" ## Backup the Principal database $Backup = new-object "Microsoft.SqlServer.Management.Smo.Backup" $BkFile = new-object "Microsoft.SqlServer.Management.Smo.BackupDeviceItem" $BkFile.DeviceType = 'File' $BkFile.Name = [System.IO.Path]::Combine($BackupPath, $BkName) $BKFileName = $BkFile.Name $Backup.Devices.Add($BkFile) $Backup.Database = $Database $Backup.Action = 'Database' $Backup.Initialize = 1 $Backup.BackupSetDescription = "Backup of database $Database" $Backup.BackupSetName = "$Database Backup" $Backup.PercentCompleteNotification = 5 $Backup.SqlBackup($Srv) if (!$error){ write-host "`tDatabase $Database backed up to $BkFileName" -f green return $BkFileName } else { RaisError "`tDatabase $Database backup returned an error." }