11

I wrote a little powershell function that executes Get-EventLog against remote servers. On some servers this seems to just hang and never times out. Can I timeout a powershell function call? I see how to do this against a different process, but i want to do this for a power shell function.

thanks

#######################
function Get-Alert4
{
    param($computer)
    $ret = Get-EventLog application -after (get-date).addHours(-2) -computer $computer | select-string -inputobject{$_.message} -pattern "Some Error String" | select-object List
    return $ret   
} #

3 Answers 3

25

You can implement timeouts by using a background job like so:

function Get-Alert4($computer, $timeout = 30)
{
  $time = (Get-Date).AddHours(-2)
  $job = Start-Job { param($c) Get-EventLog Application -CN $c -After $time | 
                     Select-String "Some err string" -inputobject{$_.message} |
                     Select-Object List } -ArgumentList $computer

  Wait-Job $job -Timeout $timeout
  Stop-Job $job 
  Receive-Job $job
  Remove-Job $job
}
Sign up to request clarification or add additional context in comments.

3 Comments

Does he need a Stop-Job after the Wait-Job? If the timeout expires the job continues to run...
Sheesh, picky, picky. I suppose you want a remove-job in there to clean up nicely too. :-)
Try the updated code. You can pass parameters into the Start-Job scriptblock using the ArgumentList parameter.
4

FYI - your argumentlist is only good for one parameter. If you want to pass more than one argument to the job, you have to pass them as an array:

  $job = Start-Job { param($c, $t) Get-EventLog Application -CN $c -After $t | 
                     Select-String "Some err string" -inputobject{$_.message} |
                     Select-Object List } -ArgumentList @($computer, $time)

Comments

0

This is a one liner (due to semi-colons) that will display a count down while pausing similar (but not the same) as the timeout cmd command

$NumOfSecs = 15; $n = $NumOfSecs; write-host "Starting in " -NoNewLine; do {if($n -lt $NumOfSecs) {write-host ", " -NoNewLine}; write-host $n -NoNewLine; $n = $n - 1; Start-Sleep 1} while ($n -gt 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.