title: Powershell command timeout
body: <p>I am trying to execute a function or a scriptblock in powershell and set a timeout for the execution.</p>
  
  <p>Basically I have the following (translated into pseudocode):</p>
  
  <pre><code>function query{
      #query remote system for something
  }
  
  $computerList = Get-Content "C:\scripts\computers.txt"
  
  foreach ($computer in $computerList){
      $result = query
      #do something with $result
  }
  </code></pre>
  
  <p>The query can range from a WMI query using Get-WmiObject to a HTTP request and the script has to run in a mixed environment, which includes Windows and Unix machines which do not all have a HTTP interface.
  Some of the queries will therefore necessarily hang or take a VERY long time to return.
  In my quest for optimization I have written the following:</p>
  
  <pre><code>$blockofcode = {
      #query remote system for something
  }
  
  foreach ($computer in $computerList){
      $Job = Start-Job -ScriptBlock $blockofcode -ArgumentList $computer
      Wait-Job $Job.ID -Timeout 10 | out-null
      $result = Receive-Job $Job.ID
      #do something with result
  }
  </code></pre>
  
  <p>But unfortunately jobs seem to carry a LOT of overhead. In my tests a query that executes in 1.066 seconds (according to timers inside $blockofcode)  took 6.964 seconds to return a result when executed as a Job. Of course it works, but I would really like to reduce that overhead. I could also start all jobs together and then wait for them to finish, but the jobs can still hang or take ridiculous amounts to time to complete.</p>
  
  <p>So, on to the question: is there any way to execute a statement, function, scriptblock or even a script with a timeout that does not comprise the kind of overhead that comes with jobs? If possible I would like to run the commands in parallel, but that is not a deal-breaker.</p>
  
  <p>Any help or hints would be greatly appreciated!</p>
  
  <p>EDIT: running powershell V3 in a mixed windows/unix environment</p>