如何使用powershell备份我的mssql数据库

时间:2015-03-14 23:44:16

标签: sql-server powershell powershell-v2.0 database-backups

我在运行PowerShell脚本备份数据库的任何时候都会遇到此错误。我似乎无法弄清问题是什么。任何帮助都将非常感激。

Exception calling "SqlBackup" with "1" argument(s): "Backup failed for Server 'MyServer'. "
At C:\Users\hp1\Desktop\scripts\backup.ps1:28 char:5
+     $smoBackup.SqlBackup($server)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FailedOperationException

我的powershell脚本如下所示:

param(
    $serverName,
    $backupDirectory,
    $daysToStoreBackups
)

[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

$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $serverName
$dbs = $server.Databases
foreach ($database in $dbs | where { $_.IsSystemObject -eq $False })
{
    if($db.Name -ne "tempdb") #We don't want to backup the tempdb database 
     {
    $dbName = $database.Name

    $timestamp = Get-Date -format yyyy-MM-dd-HHmmss
    $targetPath = $backupDirectory + "\" + $dbName + "_" + $timestamp + ".bak"

    $smoBackup = New-Object ("Microsoft.SqlServer.Management.Smo.Backup")
    $smoBackup.Action = "Database"
    $smoBackup.BackupSetDescription = "Full Backup of " + $dbName
    $smoBackup.BackupSetName = $dbName + " Backup"
    $smoBackup.Database = $dbName
    $smoBackup.MediaDescription = "Disk"
    $smoBackup.Devices.AddDevice($targetPath, "File")
    $smoBackup.SqlBackup($server)
    }
    #"backed up $dbName ($serverName) to $targetPath"
}

Get-ChildItem "$backupDirectory\*.bak" |? { $_.lastwritetime -le (Get-Date).AddDays(-$daysToStoreBackups)} |% {Remove-Item $_ -force }
"removed all previous backups older than $daysToStoreBackups days"

2 个答案:

答案 0 :(得分:2)

我发现了问题。它与SQL Server服务帐户的目标文件夹的权限有关。备份时的一个常见问题是检查SQL Server服务帐户是否具有访问目标的正确权限。 PowerShell只是将T-SQL提交给SQL Server来执行,因此运行该脚本的帐户必须具有必需的权限。一旦我给它读/写一切运行良好

答案 1 :(得分:0)

mkdir D:\国王    Invoke-Sqlcmd -Query"备份数据库Neelamsainaidu to disk =' D:\ kings \ Neelammss.BAK'" -ServerInstance MSWORK-PC -Database Neelamsainaidu