3

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?

larryq
  • 15,713
  • 38
  • 121
  • 190

1 Answers1

6

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 
}
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • Thank you Keith. I had neglected to add the param($..) bit at the start of the script. May I ask how I can pass in a splatted variable, whereby in addition to `$Computer` above I'm also passing in a variable named `FORCESTOP`, defined in the main script like so: `$FORCESTOP = @{force=$force}` – larryq Sep 24 '12 at 20:42
  • Splatting is an operation that you do on a cmdlet from a hashtable. Just pass in a hashtable of parameters and you can then splat that hashtable onto an command. You could pass in the parameters individually e.g. `params($ComputerName, [switch]$ForceStop)`... – Keith Hill Sep 24 '12 at 21:22