开发者

How to timeout PowerShell function call

I wrote a开发者_JS百科 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   
} #


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
}


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)


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜