Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
add comment

1 Answer

up vote 5 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
add comment

Your Answer

 
discard

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.