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

lar*_*ryq 3 powershell arguments cmdlet start-job

我是Start-Jobcmdlet的新手,我在调用带有cmdlet的脚本块时遇到了问题.这是我到目前为止所拥有的:

    Start-Job -ScriptBlock {
       $ServiceObj = Get-Service -Name $ServiceName -ComputerName $Computer -ErrorAction Stop   
       Stop-Service -InputObj $ServiceObj -erroraction stop 
    }
Run Code Online (Sandbox Code Playgroud)

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

foreach($Computer in $ComputerNames) {
  foreach($ServiceName in $ServiceNames) {
   #..call snippet above
  }
 }
Run Code Online (Sandbox Code Playgroud)

我曾尝试使用-ArgumentListwhen调用我的脚本块,但也没有运气.我确定我错过了什么?

Kei*_*ill 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
Run Code Online (Sandbox Code Playgroud)

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

Start-Job -ScriptBlock {
   $ServiceObj = Get-Service -Name $ServiceName -CN $using:Computer -ErrorAction Stop
   Stop-Service -InputObj $ServiceObj -erroraction stop 
}
Run Code Online (Sandbox Code Playgroud)