PowerShell:无法将SMO.server类型转换为SMO.server类型

时间:2015-04-10 14:43:24

标签: powershell sql-server-2008-r2 powershell-v3.0 smo

我从PowerShell获取错误:

Cannot convert argument "srv", with value: "[DBADEV\SQL2008r2]", for "SqlBackup" to type "Microsoft.SqlServer.Management.Smo.Server": "Cannot convert the "[DBADEV\SQL2008r2]" value of type 
"Microsoft.SqlServer.Management.Smo.Server" to type "Microsoft.SqlServer.Management.Smo.Server"."
At line:23 char:1
+ $backup.SqlBackup($srv)
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

我正在尝试编写PowerShell脚本,以便从我们的Production框和DBADEV框中恢复数据库。下面是我正在使用的代码,然后产生错误。

#Clear Screen
cls

#load assemblies
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
$ErrorActionPreference = "Inquire"

# Restore [SQLSRV2k8-0102\SQL2008] instance

$BackupFile = Get-ChildItem "\\NetworkShare\r`$\MSSQL10.SQL2008\MSSQL\Backup\AdventureWorks2008r2" | select -Last 1

$BackupFile

$srv = New-Object Microsoft.SqlServer.Management.Smo.Server("DBADEV\SQL2008r2")
$res = New-Object Microsoft.SqlServer.Management.Smo.Restore
$backup = New-Object Microsoft.SqlServer.Management.Smo.Backup

$Backup.Devices.AddDevice($BackupFile, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
$Backup.Database = "AdventureWorks2008r2"
$Backup.Action = [Microsoft.SqlServer.Management.Smo.BackupActionType]::Database
$backup.Initialize = $true
$backup.SqlBackup($srv)
$srv.Databases["AdventureWorks2008r2"].Drop()

$res.Devices.AddDevice($BackupFile, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
$res.Database = "AdventureWorks2008r2"
$res.NoRecovery = $true
$res.SqlRestore($srv)

这个错误对我来说似乎有点神秘(大多数PowerShell错误也是如此)。有关为何发生这种情况的任何想法?当我在这里使用Mike Fal的powershell脚本时,我也遇到了错误:http://www.mikefal.net/2014/07/22/restoreautomation-powershell-module/

似乎让我遇到此错误的一件事是将“DBADEV \ SQL2008r2”直接传递给SQLRestore, 即$res.SqlRestore("DBADEV\SQL2008r2") instead of $res.SqlRestore($srv)

现在生成错误,指出“服务器'还原失败'DBADEV \ SQL2008r2'

1 个答案:

答案 0 :(得分:0)

根据我的经验,出现这种错误是因为变量中的名称/数据类型错误。

我会尝试在“DBADEV \ SQL2008r2”

中逃避\

或尝试我在MSDN上找到的内容

$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
Write-Host $srv.Information.Version

所以看起来像

New-Object Microsoft.SqlServer.Management.Smo.Server("(DBADEV\SQL2008r2)")