我正在尝试备份SQL数据库,但奇怪的是占用空间,我可以用powershell备份的数据库很少,但很少我收到错误
Exception calling "SqlBackup" with "1" argument(s): "Backup failed for Server
'Server1'. "
At C:\_Scripts\defaultbackup.ps1:40 char:1
+ $smoBackup.SqlBackup($server)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FailedOperationException
$dbToBackup = "test"
#clear screen
cls
#load assemblies
#note need to load SqlServer.SmoExtended to use SMO backup in SQL Server 2008
#otherwise may get this error
#Cannot find type [Microsoft.SqlServer.Management.Smo.Backup]: make sure
#the assembly containing this type is loaded.
[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") | Out-
Null
#create a new server object
$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") "(local)"
$backupDirectory = $server.Settings.BackupDirectory
"Default Backup Directory: " + $backupDirectory
$db = $server.Databases[$dbToBackup]
$dbName = $db.Name
$timestamp = Get-Date -format yyyyMMddHHmmss
$smoBackup = New-Object ("Microsoft.SqlServer.Management.Smo.Backup")
#BackupActionType specifies the type of backup.
#Options are Database, Files, Log
#This belongs in Microsoft.SqlServer.SmoExtended assembly
$smoBackup.Action = "Database"
$smoBackup.BackupSetDescription = "Full Backup of " + $dbName
$smoBackup.BackupSetName = $dbName + " Backup"
$smoBackup.Database = $dbName
$smoBackup.MediaDescription = "Disk"
$smoBackup.Devices.AddDevice($backupDirectory + "\" + $dbName + "_" + $timestamp +
".bak",
"File")
$smoBackup.SqlBackup($server)
#let's confirm, let's list list all backup files
$directory = Get-ChildItem $backupDirectory
$ smoBackup.Devices.AddDevice($ backupDirectory +" \" + $ dbName +" _" + $ timestamp +" .bak",&# 34;文件&#34)
$ smoBackup.SqlBackup($服务器)
$ directory = Get-ChildItem $ backupDirectory
$backupFilesList = $directory | where {$_.extension -eq ".bak"}
$backupFilesList | Format-Table Name, LastWriteTime
$backupFilesList = $directory | where {$_.extension -eq ".bak"}
$backupFilesList | Format-Table Name, LastWriteTime
答案 0 :(得分:1)
将
$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") "(local)"
替换为
$srv = New-Object ("Microsoft.SqlServer.Management.Smo.Server") "(local)"
$conContext = $srv.ConnectionContext
$conContext.LoginSecure = $True
$conContext.ConnectTimeout = 0
$server = new-object Microsoft.SqlServer.Management.Smo.Server($conContext)
答案 1 :(得分:1)
由于你可以备份少数几个失败,似乎脚本很好。为什么不添加异常处理以捕获确切的错误。 您可能需要修改代码,如下所示
Try
{
$smoBackup.SqlBackup($server
}
Catch
{
Write-Output $_.Exception.InnerException
}