Question

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?

Was it helpful?

Solution

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 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top