To start with im not an expert on database and scripting for powershell. I found a powershell script for database restore over the internet. Some are added by me based on my research. The problem that im having is whenever i ran the script it runs sometimes and when i restart the machine it throws out a lot of error. Also one more thing when i set this on task scheduler i'm getting error events of login failed for user 'xxxx'. failed to open the explicitly database. Maybe someone can help me with this. Thanks in advance.
script below:
#load assemblies[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
#Need SmoExtended for backup
[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
$server = "SQL2016"
$targetDB = "TestDB"
$assemblySqlServerSmoExtendedFullName = "Microsoft.SqlServer.SmoExtended, Version=13.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
$srvconn = new-object Microsoft.SqlServer.Management.Common.ServerConnection
$srvconn.ServerInstance = $server
$srvconn.LoginSecure =$false
$srvconn.Login = "sa"
$srvconn.Password = "password"
$latestDB = Get-ChildItem C:\dbbackuptest\xxx_*.bak | sort LastWriteTime | select -last 1
#This backup file must be a local path for this to work, apparently!
#$bakfile = 'C:\dbbackuptest\xxx.bak'
#Connects to the above SQL server via SMO
$srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') $srvconn
#Creates a restore object
$RestoreObject = new-object('Microsoft.SqlServer.Management.Smo.Restore')
#Creates a Backup Device Item, and appends them to the Restore Object... I dont understand this part yet.
$bdi = new-object ('Microsoft.SqlServer.Management.Smo.BackupDeviceItem') ($bakfile, 'File')
$RestoreObject.Devices.Add($bdi)
#Reads the backup file to retirve the old logical names of .mdf and .ldf, creates variables for them
$fl = $RestoreObject.ReadFileList($srv)
$RestoreMDF = $fl.select("Type = 'D'")[0].LogicalName
$RestoreLDF = $fl.select("Type = 'L'")[0].LogicalName
$RelocateData = New-Object "Microsoft.SqlServer.Management.Smo.RelocateFile,$assemblySqlServerSmoExtendedFullName"("$RestoreMDF", "C:\dbbackuptest\$TargetDB.mdf")
$RelocateLog = New-Object "Microsoft.SqlServer.Management.Smo.RelocateFile,$assemblySqlServerSmoExtendedFullName"("$RestoreLDF", "C:\dbbackuptest\$TargetDB.ldf")
#Performs the restore
Restore-SqlDatabase -Database $targetDB -ServerInstance $srvconn -BackupFile $latestDB -ReplaceDatabase -RelocateFile @($RelocateData,$RelocateLog)