如何超时PowerShell函数调用

Cha*_*had 11 powershell powershell-2.0

我写了一个小的powershell函数,它对远程服务器执行Get-EventLog.在某些服务器上,这似乎只是挂起,永远不会超时.我可以超时一个powershell函数调用吗?我看到如何针对不同的进程执行此操作,但我想为power shell函数执行此操作.

谢谢

#######################
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   
} #
Run Code Online (Sandbox Code Playgroud)

Kei*_*ill 25

您可以使用后台作业实现超时,如下所示:

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
}
Run Code Online (Sandbox Code Playgroud)

  • 等待工作后他需要停工吗?如果超时到期,则作业继续运行... (3认同)
  • Sheesh,挑剔,挑剔.我想你想要一个删除工作也很好地清理.:-) (2认同)