3

我正在尝试使用 SMO 通过 Powershell 还原数据库,但是当我尝试定义和使用服务器对象时,它给了我以下错误:

Cannot convert argument "srv", with value: "[MJNHNX4]", for "SqlRestore" to type "Microsoft.SqlServer.Management.Smo.Server": "Cannot convert the "[MJNHNX4]" value of type 
"Microsoft.SqlServer.Management.Smo.Server" to type "Microsoft.SqlServer.Management.Smo.Server"."
At line:38 char:1
+ $smoRestore.SqlRestore($server)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

这是我的完整代码(内容不多):

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null

#clear screen
cls

#get backup file
$backupFile = "D:\databases\Perfmon.bak"
$servername = "MJNHNX4" 
$server = New-Object Microsoft.SqlServer.Management.Smo.Server($servername)
$backupDevice = New-Object ("Microsoft.SqlServer.Management.Smo.BackupDeviceItem") ($backupFile, "File")
$smoRestore = new-object("Microsoft.SqlServer.Management.Smo.Restore")

#settings for restore
$smoRestore.NoRecovery = $false;
$smoRestore.ReplaceDatabase = $true;
$smoRestore.Action = "Database"

#show every 10% progress
$smoRestore.PercentCompleteNotification = 10;

$smoRestore.Devices.Add($backupDevice)

#read db name from the backup file's backup header
$smoRestoreDetails = $smoRestore.ReadBackupHeader($server)

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

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

#restore
$smoRestore.SqlRestore($server)

"Done"

无论我尝试将什么传递给 Microsoft.SqlServer.Management.Smo.Server,都会发生错误,我真的不确定为什么它会给我那个特定的错误。我已经阅读了有关服务器构造器的 TechNet 文章,但我真的不知道那里发生了什么。有任何想法吗?

4

1 回答 1

2

在进一步测试和阅读 SMO 语法之后,看起来我不需要将 $server 定义为新对象。相反,只需将服务器的名称传递给 $server 就可以了。

于 2013-09-10T14:56:25.603 回答