Powershell SMO SQL 服务器还原问题

Issue with Powershell SMO SQL Server restore

我运行遇到了执行 Powershell SQL 恢复的问题。我有这个代码

[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

$backupFile = 'C:\Temp\User_20191029152532.bak'

$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") "(local)"
$backupDevice = New-Object("Microsoft.SqlServer.Management.Smo.BackupDeviceItem") ($backupFile, "File")
$smoRestore = new-object("Microsoft.SqlServer.Management.Smo.Restore")

$smoRestore.NoRecovery = $false;
$smoRestore.ReplaceDatabase = $true;
$smoRestore.Action = "Database"
$smoRestorePercentCompleteNotification = 10;
$smoRestore.Devices.Add($backupDevice)

$smoRestoreDetails = $smoRestore.ReadBackupHeader($server)

"Database Name from Backup Header : " +$smoRestoreDetails.Rows[0]["DatabaseName"]

$smoRestore.Database =$smoRestoreDetails.Rows[0]["DatabaseName"]

$smoRestoreFile = New-Object("Microsoft.SqlServer.Management.Smo.RelocateFile")
$smoRestoreLog = New-Object("Microsoft.SqlServer.Management.Smo.RelocateFile")

$smoRestoreFile.LogicalFileName = $smoRestoreDetails.Rows[0]["DatabaseName"]
$smoRestoreFile.PhysicalFileName = $server.Information.MasterDBPath + "\" + $smoRestore.Database + "_Data.mdf"
$smoRestoreLog.LogicalFileName = $smoRestoreDetails.Rows[0]["DatabaseName"] + "_Log"
$smoRestoreLog.PhysicalFileName = $server.Information.MasterDBLogPath + "\" + $smoRestore.Database + "_Log.ldf"
$smoRestore.RelocateFiles.Add($smoRestoreFile)
$smoRestore.RelocateFiles.Add($smoRestoreLog)

$smoRestore.SqlRestore($server)

如果我 运行 一切正常。但是,我想提供一个要恢复备份的变量。所以我将代码的顶部更改为:

$path = 'C:\Temp'
$db_name = 'User'
$file = Get-ChildItem $path '*.bak' | Select-Object basename | Where-Object {$_.basename -like $db_name + '*' }

$backupFile = $path + '\' + $file

进行此更改后,我开始收到以下错误。

Exception calling "ReadBackupHeader" with "1" argument(s): "An exception occurred while executing a Transact-SQL statement or batch."

At line:23 char:1
+ $smoRestoreDetails = $smoRestore.ReadBackupHeader($server)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ExecutionFailureException

不太确定为什么它不接受我传递的 $file 变量。如果我查看变量,它会返回正确的值。

我的愚蠢问题。 $file 不包括扩展名。将 .bak 添加到 $file 解决了这个问题。