Powershell还原数据库

时间:2019-12-02 20:00:39

标签: sql-server powershell

尝试将脚本放在一起运行,该脚本将运行并在位置中搜索最新的数据库文件,然后将其还原到SQL Server。我的搜索功能运行良好,但是无法恢复数据库。

import-module sqlps
#update path for to actual backup location
$path = "D:\Temp"
$logPath = "D:\Log" #change to proper log path when running
$backupPath = "D:\backup" # shouldn't need but putting here just encase
$server = "server1"
$database = 'DBname'
#$database = gc( 'C:\Database Recovery Script\'+$server+' Database list.txt' )
#$dataFileLocation = "D:\SqlData\$data.mdf"
$password = 'xxxxxxx'

foreach ($data in $database)
{
#For testing use the QBW filter
#Once testing is over swithc to proper filter.
$filter = '*server1_DBname_FULLL*'
#$filter = '*_'+$Server+'_'+$data+'_FULL*'
$latest = get-childitem -Path $path -Filter $filter |
    where-object { -not $_.PSIsContainer } |
    sort-object -Property $_.CreationTime |
    Select-Object -first 3
$latest.fullname


$dataFileLocation = "D:\SqlData\$data.mdf"
$logFileLocation = "L:\SqlLogs\$data.ldf"

$sql = @"
USE [master]

RESTORE DATABASE "$data" `
FROM DISK = N'$latest.fullname' `
WITH FILE = 1, `
     MOVE N'CurrentDB' TO N'$dataFileLocation', `
     MOVE N'CurrentDB_log' TO N'$logFileLocation', `
     NOUNLOAD, NORECOVERY, REPLACE, STATS = 5, PASSWORD = '$password' ` `
"@

 invoke-sqlcmd -ServerInstance "localhost\tedbdev01" -Query $sql -Username "xxxx" -Password "xxxx"
}

运行脚本时,出现错误,提示它无法打开备份设备。当我仅在SQL Server管理中心中运行脚本时,会得到

  

3241级第3行,状态0,第4行的短信
  设备'D:\ Temp \ 20191020_045728_AWSCSQL02_DB21387_FULL.sqb'上的媒体系列
  格式不正确。 SQL Server无法处理此媒体系列。
  消息3013,第16级,状态1,第4行
  RESTORE DATABASE异常终止。

如果有人可以给我关于解决该问题的建议。

0 个答案:

没有答案