#Loading required assemblies
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null
#Setting up arguments to variables
$Server = $args[0];
$BackupFile = $args[1];
#Handle Errors (if in case)
Trap
{
$err = $_.Exception;
while ( $err.InnerException )
{
$err = $err.InnerException;
write-output ("Oops!!! There is a Problem -> " + $err.Message);
}
return;
}
#If arguments are insufficient
if($args.count -ne 2)
{
write-output "Usage:"
write-output 'Syntax : "ServerName" "Backup file path to use"'
write-output 'Example : "Rami-Server" "C:\BackUp\SampleDB_full_2011-10-06-04-04-37.bak"'
return;
};
if(!(Test-Path $BackupFile))
{
Write-Output ("InValid Backup File Path");
return;
}
#Create SMO Objects
$server = New-Object Microsoft.SqlServer.Management.Smo.Server $Server
$backupDevice = New-Object Microsoft.SqlServer.Management.Smo.BackupDeviceItem $BackupFile, "File"
$Restore = New-object Microsoft.SqlServer.Management.Smo.Restore
#Set properties for Restore
$Restore.NoRecovery = $false;
$Restore.Devices.Add($backupDevice)
$RestoreDetails = $Restore.ReadBackupHeader($server)
#Set Database Name
$Restore.Database = Get-ChildItem $BackupFile | % {$_.BaseName}
#Set Relocation Files
$RestoreDBFile = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile
$RestoreLog = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile
#Set Logical and Physical File Names
$RestoreDBFile.LogicalFileName = $RestoreDetails.Rows[0]["DatabaseName"]
$RestoreDBFile.PhysicalFileName = $server.Information.MasterDBPath + "\" + $Restore.Database + ".mdf"
$RestoreLog.LogicalFileName = $RestoreDetails.Rows[0]["DatabaseName"] + "_Log"
$RestoreLog.PhysicalFileName = $server.Information.MasterDBLogPath + "\" + $Restore.Database + "_Log.ldf"
Write-Output ("Restore Started at: " + (Get-Date -format yyyy-MM-dd-HH:mm:ss));
$Restore.RelocateFiles.Add($RestoreDBFile)
$Restore.RelocateFiles.Add($RestoreLog)
#Restore database
$Restore.SqlRestore($server)
Write-Output ("Restore Ended at: " + (Get-Date -format yyyy-MM-dd-HH:mm:ss));
Write-Output ("Restore completed with Database Name " + $Restore.Database);Code was self explanatory, but I would like to narrate the common steps which I took in constructing this code –
Now you can go and check in SSMS, newly restored database will be listed under databases node.