Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to timeout PowerShell function call

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   
} #
like image 777
Chad Avatar asked Jan 10 '11 20:01

Chad


People also ask

Does PowerShell have a timeout?

In Windows PowerShell 2.0, the default value of the IdleTimeout parameter is 240000 (4 minutes).

How do you wait for a process to finish in PowerShell?

The Wait-Process cmdlet waits for one or more running processes to be stopped before accepting input. In the PowerShell console, this cmdlet suppresses the command prompt until the processes are stopped. You can specify a process by process name or process ID (PID), or pipe a process object to Wait-Process .

How do I pause PowerShell?

The most commonly used pause command is by far, Start-Sleep . This command takes two simple inputs, which are -Seconds and -Milliseconds . Seconds can be a System. Double number value while milliseconds takes only System.


1 Answers

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
}
like image 169
Keith Hill Avatar answered Sep 29 '22 12:09

Keith Hill