简体   繁体   中英

Restore MS SQL Server Database using powershell and task scheduler

I have a SQL Database that I want to restore nightly on a server that is different from the backup server. I am trying to accomplish this using a powershell script launched at a specific time via task scheduler. I have a powershell script that will restore a MS SQL database:

$SharedFolder = "C:\Backups"

$RelocateData = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("Database_dat", "C:\Database\XXYYZZ.mdf")

$RelocateLog = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("Database_log", "C:\Database\XXYYZZ.ldf")

Restore-SqlDatabase -ServerInstance "XXYYZZTEST" -Database "newXXYYZZ" -BackupFile "$($SharedFolder)\tuesday_backup.bak" -RelocateFile @($RelocateData,$RelocateLog) -ReplaceDatabase

Unfortunately, the first time I run this script in Powershell ISE I receive this red error:

New-Object: Cannot find type > [Microsoft.SqlServer.Management.Smo.RelocateFile]: verify that the assembly containing this type is loaded.

for each of the lines $RelocateData and $RelocateLog. The script then fails with this red error:

Restore-SqlDatabase: Object reference not set to an instance of an object.

If I run the script again without closing Powershell ISE it runs fine on every subsequent run. As soon as I close Powershell ISE and open it again the error returns on the first run then everything works ok. I have limited knowledge of powershell which hampers my search for a solution to these assembly errors.

It does not successfully run at all when launched from task scheduler but all of the task scheduler actions complete successfully. I have tried running the task as different admin users, highest priority, changing the start in folder. Nothing seemed to help and I suspect it is the issue described above regarding the assemblies.

Any thoughts/suggestions? Is there a better process for accomplishing what I am trying?

Added the line: Import-Module -Name SqlServer to load the powershell module. Script now looks like this:

Import-Module -Name SqlServer
$SharedFolder = "C:\Backups"
$RelocateData = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("Database_dat", "C:\Database\XXYYZZ.mdf")
$RelocateLog = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("Database_log", "C:\Database\XXYYZZ.ldf")
Restore-SqlDatabase -ServerInstance "XXYYZZTEST" -Database "newXXYYZZ" -BackupFile "$($SharedFolder)\tuesday_backup.bak" -RelocateFile @($RelocateData,$RelocateLog) -ReplaceDatabase

The script now runs error free in both powershell and task scheduler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM