Powershell 在尝试使用 SMO.Backup.AddDevice 时抛出转换异常

Powershell throws conversion exception when trying to use SMO.Backup.AddDevice

我完全被这个弄糊涂了。我正在尝试使用 SMO 程序集编写一个简单的数据库还原脚本。

当我尝试添加设备并传递路径时,如下所示:

$backup.Devices.AddDevice($path, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)

我遇到一个奇怪的异常:

Cannot convert argument "1", with value: "File", for "AddDevice" to type "Microsoft.SqlServer.Management.Smo.DeviceType": "Cannot convert value "File" to type "Microsoft.SqlServer.Management.Smo.DeviceType". Error: "Invalid cast from 'Microsoft.SqlServer.Mana gement.Smo.DeviceType' to 'Microsoft.SqlServer.Management.Smo.DeviceType'."" At D\Automatisk inläsning\AutoImportPowershell.ps1:41 char:26 + $backup.Devices.AddDevice <<<< ($path, [Microsoft.SqlServer.Management.Smo.DeviceType]::File) + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

这是完整的脚本:

#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

#HARDCODED VARIABLES:
$path = "C:\TestFolder\Bakfile.bak"
$server = "(local)"
$databas = "MyDatabase"

#SMO OBJECTS:
$srv = new-object Microsoft.SqlServer.Management.Smo.Server($server)
$res = new-object Microsoft.SqlServer.Management.Smo.Restore
$backup = new-object Microsoft.SqlServer.Management.Smo.Backup

#STARTING RESTORE:
$backup.Devices.AddDevice($path, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
$backup.Database = $databas
$backup.Action = [Microsoft.SqlServer.Management.Smo.BackupActionType]::Database
$backup.Initialize = $TRUE
$backup.SqlBackup($srv)

$res.Devices.AddDevice($path, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
$res.Database = $databas
$res.NoRecovery = $TRUE
$res.SqlRestore($srv)

令我困惑的是错误消息本身 Invalid cast from 'Microsoft.SqlServer.Mana gement.Smo.DeviceType' 到 'Microsoft.SqlServer.Management.Smo.DeviceType'。这些对我来说听起来像是同一类型!

你能测试添加:

Add-Type -AssemblyName  Microsoft.SqlServer.Management.Common
Add-Type -AssemblyName  Microsoft.SqlServer.Management.Smo

在您的 #ASSEMBLIES: 小组的末尾。

然后替换:

$backup.Devices.AddDevice($path, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)

$bdi = new-object Microsoft.SqlServer.Management.Smo.BackupDeviceItem($path, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
$backup.Devices.Add($bdi)

备份设备项