我正在尝试使用以下方法备份mdf文件,但在将数据库附加回服务器时脚本失败。我已经开始在我们的新服务器(Windows Server 2008 R2)中遇到此问题。以下是scriplet。
#load assemblies
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
write-host "Initializing..."
#Initialization section
$serverName = "sqlserver\SQL2005"
$databaseName = "myDatabase"
$sourceLocation = "\\sqlserver\dbPath\myDatabase"
$attachDBSourceLocation = "D:\Sql 2005 Databases\dbPath\myDatabase"
$mdfFileName = $sourceLocation + "\" + $databaseName + ".mdf"
$attachMDFFileName = $attachDBSourceLocation + "\" + $databaseName + ".mdf"
$ldfFileName = $sourceLocation + "\" + $databaseName + "_log.ldf"
$destLocation = read-host -prompt "Enter the destination location"
#End of Initialization section
write-host "Initialization completed"
#create a new server object
$serverConn = New-Object ("Microsoft.SqlServer.Management.Common.ServerConnection")
$serverName, "psuser", "psuser"
$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $serverConn
write-host "Server object created"
$server.Databases["myDatabase"].ExecuteNonQuery("ALTER DATABASE myDatabase SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE", [Microsoft.SqlServer.Management.Common.ExecutionTypes]::Default)
#detach the database to be copied. Drop connections if any by changing the connection mode to single user mode
$server.DetachDatabase($databaseName, $true)
write-host "Database $databaseName detached"
#copy the database (backup)
write-host "Started copying database '$mdfFileName' to '$destLocation'. Please wait..."
copy-item $mdfFileName -Destination $destLocation
write-host "Database '$databaseName' copied to '$destLocation'"
#delete the log file
remove-item -path $ldfFileName
write-host "Database LDF file deleted" #attach the mdf file without ldf so that a new ldf is automatically created
write-host "Attaching Database '$databaseName'. Please wait..."
$strColl = New-Object ("System.Collections.Specialized.StringCollection")
[void]$strColl.Add($attachMDFFileName)
$server.AttachDatabase($databaseName, $strColl, [Microsoft.SqlServer.Management.Smo.AttachOptions]::NewBroker)
write-host "Database attached successfully"
write-host "Shrinking Database '$databaseName'. Please wait..."
$server.Databases[$databaseName].ExecuteNonQuery("DBCC SHRINKDATABASE ($databaseName, 5)")
write-host "Database shrinked successfully"
write-host "Database backup successful"
答案 0 :(得分:0)
您确定需要重载超载吗?从该方法的重载列表:
如果您要重新附加现有数据库,只需要指定数据库名称和文件集合。