Start-Job script block-- how to call cmdlets with arguments?

larryq picture larryq · Sep 24, 2012 · Viewed 8.6k times · Source

I'm new to the Start-Job cmdlet and am having trouble calling a script block with cmdlets in it that take arguments. Here's what I have so far:

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

I'm seeing errors when I run receive-job that the -ComputerName argument is null or empty, and the -InputObj argument is null or empty. In neither case is that so. The snippet above is being called from inside two foreach loops:

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

I've tried using the -ArgumentList when calling my script block but no luck there either. I'm sure I'm missing something?

Answer

Keith Hill picture Keith Hill · Sep 24, 2012

You do need to use ArgumentList (unless you're on PowerShell V3) e.g.:

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

If you're using PowerShell V3, you can use the using variable qualifier e.g.:

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