2/6/10

PowerShell Asynchronous Background Jobs

PowerShell Background Jobs - MSDN.
Requires PowerShell v2.

Job Cmdlets
start-job
get-job
receive-job
stop-job
start-job {
  #...
}

#with parameters
start-job {param($p1, $p2)
  $p1
  $p2
} -argumentList 'foo', 123

#output
foo
123

#execute N times
start-job {
  1..3 |
    %{
        (get-date).toString('HH:mm:ss')
        sleep 1
     }
}

#output
20:32:51
20:32:52
20:32:53

#execute N times with script block begin-process-end clause
start-job {
  begin
  {
    'begin script...'
  }
  process
  {
    1..3 | %{(get-date).toString('HH:mm:ss'); sleep 1;}
  }
  end
  {
    'end script...'
  }
}

#output
begin script...
20:35:42
20:35:43
20:35:44
end script...

#infinite loop, stop job during sleep interval
start-job {param($sleep)
  while ($true)
  {
    #...

    $now = get-date
    'sleep {0}, {1} - {2}' -f $sleep, $now.toString('HH:mm:ss'), $now.addSeconds($sleep).toString('HH:mm:ss')
    sleep $sleep
  }
} -argumentList 60

#output
sleep 60, 20:41:06 - 20:42:06
sleep 60, 20:42:06 - 20:43:06

No comments:

Post a Comment