Hello,
I am trying to create a Powershell (v4) script to restore a database to a SQL Server 2012 Instance. I am able to get the database to restore, but i have some complications. If i use the .SqlRestore method, the restore errors out because of the connection query time out (takes longer than 10 minutes to restore). So i have to use the .SqlRestoreAsync.
The problem with .SqlRestoreAsync is that i want to do more work after the restore is complete. I have been unable to figure out how to get the status of the restore, including when it is complete, as well as any error or exceptions that might occur during the restore. Then, when the restore is complete, i would like to move on in the script to do more work. Here is the restore portion of my script:
#Load SQL PowerShell Module
Import-Module “sqlps” -DisableNameChecking
#Set variables
$gPath = "E:\SQL\PowerShell\QA_Web_Refresh"
$log = "$gPath + \$(Get-Date -Format yyyyMMdd_HHmmss)_DatabaseRestore.txt"
$Server = "SQLSERVER2012"
$srv = New-Object("Microsoft.SqlServer.Management.Smo.Server") $Server
#Restore DatabaseRestore Database from backup
$backupFile = "E:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\DB.bak"
$restoreDataPath = "G:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA"
$restoreLogPath = "F:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data"
$backupDevice = New-Object ("Microsoft.SqlServer.Management.Smo.BackupDeviceItem") ($backupFile, "File")
$backupRestore = New-Object ("Microsoft.SqlServer.Management.Smo.Restore")
$backupRestore.Database = "DatabaseRestore"
$backupRestore.NoRecovery = $fales;
$backupRestore.ReplaceDatabase = $true;
$backupRestore.Action = "Database"
$backupRestore.Devices.Add($backupDevice)
$restoreFilelist = $backupRestore.ReadFileList($srv)
foreach ($file in $restoreFilelist) {
$dbRestoreFile = New-Object("Microsoft.SqlServer.Management.Smo.RelocateFile")
$dbRestoreFile.LogicalFileName = $file.LogicalName
if ($file.Type -eq "D") {$dbRestoreFile.PhysicalFileName = "$restoreDataPath\$(Split-Path $file.PhysicalName -leaf)"}
if ($file.Type -eq "L") {$dbRestoreFile.PhysicalFileName = "$restoreLogPath\$(Split-Path $file.PhysicalName -leaf)"}
$backupRestore.RelocateFiles.Add($dbRestoreFile)
}
try {$backupRestore.SqlRestoreAsync($srv)}
catch {$_.Exception.GetBaseException().Message}
#I would like to display the progress (%) of the restore, and then when it is complete...
#Do more work ....