Start-Job脚本块 - 如何使用参数调用cmdlet?

时间:2012-09-24 19:43:06

标签: powershell arguments cmdlet start-job

我是Start-Job cmdlet的新用户,并且在调用带有参数的cmdlet的脚本块时遇到问题。这是我到目前为止所做的:

    Start-Job -ScriptBlock {
       $ServiceObj = Get-Service -Name $ServiceName -ComputerName $Computer -ErrorAction Stop   
       Stop-Service -InputObj $ServiceObj -erroraction stop 
    }

当我运行receive-job -ComputerName参数为null或为空时,我发现错误,-InputObj参数为null或为空。在这两种情况都不是这样。上面的代码片段是从两个foreach循环内部调用的:

foreach($Computer in $ComputerNames) {
  foreach($ServiceName in $ServiceNames) {
   #..call snippet above
  }
 }

我在调用脚本块时尝试使用-ArgumentList,但也没有运气。我确定我错过了什么?

1 个答案:

答案 0 :(得分:6)

您需要使用ArgumentList(除非您使用的是PowerShell V3),例如:

Start-Job -ScriptBlock {param($ComputerName)
   $ServiceObj = Get-Service -Name $ServiceName -CN $ComputerName -ErrorAction Stop
   Stop-Service -InputObj $ServiceObj -erroraction stop 
} -ArgumentList $Computer

如果您使用的是PowerShell V3,则可以使用using变量限定符,例如:

Start-Job -ScriptBlock {
   $ServiceObj = Get-Service -Name $ServiceName -CN $using:Computer -ErrorAction Stop
   Stop-Service -InputObj $ServiceObj -erroraction stop 
}
相关问题