Powershell将SQL Server数据库还原到新数据库

时间:2017-08-18 20:13:50

标签: sql-server powershell

我有一个数据库$CurrentDB,我想将$CurrentDB的备份恢复为$NewDB。 T-SQL命令如下所示:

USE [master]

ALTER DATABASE [NewDB] 
    SET SINGLE_USER WITH ROLLBACK IMMEDIATE

RESTORE DATABASE [NewDB] 
FROM DISK = N'D:\Backups\CurrentDB.bak' 
WITH FILE = 1,  
     MOVE N'CurrentDB' TO N'D:\Databases\NewDB.mdf',  
     MOVE N'CurrentDB_log' TO N'D:\Logs\NewDB_log.ldf',  
     NOUNLOAD, REPLACE, STATS = 5

ALTER DATABASE [NewDB] 
    SET MULTI_USER
GO

我正在尝试使用Restore-SqlDatabase,但我不知道如何正确-RelocateFile

$CurrentDB = "CurrentDB"
$NewDB = "NewDB"
$NewDBmdf = "NewDB.mdf"
$CurrentDBlog = "CurrentDB_log"
$NewDBldf = "NewDB_log.ldf"
$backupfile = $CurrentDB + "ToNewDB.bak"

$RelocateData = New-Object 
Microsoft.SqlServer.Management.Smo.RelocateFile($CurrentDB, $NewDBmdf)

$RelocateLog = New-Object 
Microsoft.SqlServer.Management.Smo.RelocateFile($CurrentDBlog, $NewDBldf)

Restore-SqlDatabase -ServerInstance $SQLServer -Database $NewDB -BackupFile 
$backupfile -ReplaceDatabase -NoRecovery -RelocateFile @($RelocateData, 
$RelocateLog)

我似乎无法找到我正在尝试做的事情的一个例子。我已经看到了大量恢复具有相同名称但不同文件的数据库的示例。我想要一个不同的名称和不同的文件名。我愿意接受建议。

2 个答案:

答案 0 :(得分:6)

您不必仅仅因为您使用PowerShell而使用SMO。

import-module sqlps

$database = "NewDb"
$backupLocation = "D:\Backups\CurrentDB.bak"
$dataFileLocation = "D:\Databases\NewDB.mdf"
$logFileLocation = "D:\Logs\NewDB_log.ldf"

$sql = @"

USE [master]

ALTER DATABASE [$database] 
    SET SINGLE_USER WITH ROLLBACK IMMEDIATE

RESTORE DATABASE [$database] 
FROM DISK = N'$backupLocation' 
WITH FILE = 1,  
     MOVE N'CurrentDB' TO N'$dataFileLocation',  
     MOVE N'CurrentDB_log' TO N'$logFileLocation',  
     NOUNLOAD, REPLACE, STATS = 5

ALTER DATABASE [$database] 
    SET MULTI_USER
"@

invoke-sqlcmd $sql

如果您没有安装sqlps,可以使用Powershell的System.Data.SqlClient来运行TSQL。

答案 1 :(得分:0)

$RelocateData = [Microsoft.SqlServer.Management.Smo.RelocateFile]::new($CurrentDB, $NewDBmdf)
$RelocateLog = [Microsoft.SqlServer.Management.Smo.RelocateFile]::new($CurrentDBlog, $NewDBldf)

Restore-SqlDatabase -ServerInstance $SQLServer -Database $NewDB -BackupFile $backupfile `
-ReplaceDatabase -NoRecovery -RelocateFile @($RelocateData, $RelocateLog)