Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

If I send this two-liner to Powershell

$sName = "ALG"
$service = Get-Service -computername db-name -Name $sName

I will get back information about that service on that computer. If I change the name to "db-nameXXX" (bogus name) I will get an error that the service is not found. However, I have a server that stops accepting remote-desktop sessions (I also can't connect with MS SQL Manaagement studio) and sending these commands to that machine (when in an error condition) just hangs... The script runs but never returns. I would like to have a 'time out' functionality so that at a certain point, I can output a message saying the machine is not responding. Right now, the script is not letting me do anything. I tried a start/process/end block, but as long as get-service does not come back with an error, I can't get anywhere.

share|improve this question
up vote 6 down vote accepted

Try something like this:

$sb = [scriptblock]::create("Get-Service -computername db-name -Name $sName")
$job = Start-Job -ScriptBlock $sb | Wait-Job -Timeout 10
if($job -eq $null) {
    #timed out
else {
     $service = Receive-Job $job

This will submit Get-Service as a job and wait for the job to finish. By setting a timeout on the job, if it fails to complete the return will be null. Do whatever error handling you need to if the value is null, or receive the job and drop the result in your $service variable if it completed. This will return a Deserialized.System.ServiceProcess.ServiceController object. Adjust -Timeout on Wait-Job to fit your needs.

share|improve this answer
Works. Nice idea to put a job inside a script - the job has a -timeout parameter and exits gracefully when the get-service hangs. Thanks – richard beck May 22 '13 at 20:12
Nice answer. Vote++. – Simon Catlin May 22 '13 at 20:41

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.