Take the 2-minute tour ×

I am trying to start a service in Powershell. If the service does not start within a specified time limit, the attempt to start should be killed, otherwise it should carry on as usual. How do I incorporate a timeout?

share|improve this question

closed as too localized by JNK, manojlds, casperOne Dec 19 '11 at 21:51


I googled "Powershell timeout starting service" and the first hit has an answer for you: powershellcommunity.org/Forums/tabid/54/aft/5243/Default.aspx –  JNK Dec 19 '11 at 20:39
The code posted did not work properly, which was the problem when we originally stumbled upon that link, but we were able to fix it. Thank you. –  spassen Dec 19 '11 at 20:56
add comment

1 Answer

up vote 4 down vote accepted

Implementing a timeout is a really simple thing to do using background jobs:

$timeout = [Timespan]"0:0:15"
$start = Get-Date
$j = Start-Job -ScriptBLock { Import-Module MyModule; Invoke-MyCommand}
do {
    if ($j.JobState -ne 'Running') { break} 
    $j | Receive-Job
} while (((Get-Date) - $start) -le $timeout)

This block of code will timeout after 15 seconds, but it should get you started. Basically: - Track the time - Start a job - Wait for it to be no longer running (it could have failed, so don't just wait for completed) - Receive Results while you wait - Timeout if you've been waiting too long

Hope this Helps

share|improve this answer
Thanks, works perfectly. Is there a way to use milliseconds? When I tried using "0:0:0:50" and "0:0:.5" it did not work properly. –  spassen Dec 21 '11 at 20:40
Yes, you can use milliseconds with "0:0:0.5" (you were really close, and it's annoyingly picky). You can also use [Timespan]::FromMilliseconds –  Start-Automating Dec 21 '11 at 21:31
It's $j.State instead of $j.JobState in v2. –  ranomore Feb 4 '13 at 15:31
add comment
