将参数传递给start-job中的新对象

时间:2014-11-16 08:14:09

标签: sql-server

我正在尝试同时在两个sql服务器上恢复数据库。这就是我需要在后台运行restore-sqldatabase作为工作的原因,这样我就可以同时运行第二个还原作业。

receive-job显示4个错误cannot index into a null array,将参数列表中的变量传递到脚本块中是可以的,但是将变量传递到脚本块中的新对象命令“它采用自己的参数列表“似乎是问题所在。

类似的问题与我想要完成的问题并不完全相同。任何帮助都非常感谢。

Start-Job -InitializationScript { 
#load assemblies
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
#Need SmoExtended for backup
[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
} -Name JobP -ScriptBlock {
$serverConn = new-object ("Microsoft.SqlServer.Management.Smo.Server") $($args[0])
$serverConn.ConnectionContext.StatementTimeout = 0


$RelocateData = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("$($args[1])", "$($arg[2])")
$RelocateLog = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("$($args[3])", "$($arg[4])")

Restore-SqlDatabase -InputObject $serverConn -Database $($args[5]) -BackupFile "$($args[6])" -RelocateFile @($RelocateData,$RelocateLog) -ReplaceDatabase
} -ArgumentList $ServerPrimary,$database_logical_name,$database_path,$log_logical_name,$log_path,$database,$backupfile_full_path

1 个答案:

答案 0 :(得分:0)

我要感谢stackoverflow和所有以前通过param($ p1,$ p2)处理将变量传递给脚本块的线程

我设法通过反复试验来解决问题,现在脚本正在运行。这是解决方案:

    Start-Job -InitializationScript {
    #load assemblies [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
    #Need SmoExtended for backup
 [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
} -Name JobP -ScriptBlock {

#Define the parameters to be used inside the script block, $p0 will be the first arguments in the "-ArgumentList", $p1 will be the second and so on. 
param($p0, $p1, $p2, $p3, $p4, $p5, $p6)
$serverConn = new-object ("Microsoft.SqlServer.Management.Smo.Server") $p0
$serverConn.ConnectionContext.StatementTimeout = 0

#the below variables are necessary incase you have your data and log in a different  location than the default.
$RelocateData = New-Object  Microsoft.SqlServer.Management.Smo.RelocateFile("$p1", "$p2")
$RelocateLog = New-Object   Microsoft.SqlServer.Management.Smo.RelocateFile("$p3", "$p4")

echo $p0 $p1 $p2 $p3 $p4 $p5 $p6

Restore-SqlDatabase -InputObject $serverConn -Database "$p5" -BackupFile "$p6" -RelocateFile @($RelocateData,$RelocateLog) -ReplaceDatabase
} -ArgumentList $ServerPrimary,$database_logical_name,$database_path,$log_logical_name,$log_path,$database,$backupfile_full_path