How to timeout PowerShell function call

跟風遠走 提交于 2019-12-03 06:52:05

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
}
Jimmy JoeBob Alooba

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!