gpt4 book ai didi

sql-server - 如何使用Powershell备份我的mssql数据库

转载 作者:行者123 更新时间:2023-12-02 23:44:28 24 4
gpt4 key购买 nike

每当我运行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"

最佳答案

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

关于sql-server - 如何使用Powershell备份我的mssql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29055591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com