我正在尝试使用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,我都会发生错误,我真的不确定为什么它会给我这个特定的错误。我已经阅读了Server Constructor上的TechNet文章,我真的不知道那里发生了什么。有什么想法吗?
答案 0 :(得分:1)
经过一些关于SMO语法的进一步测试和阅读后,看起来我不需要将$ server定义为新对象。相反,只需将服务器名称传递给$ server即可。