且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何设置运行PowerShell脚本的时间限制?

更新时间:2023-02-03 21:23:51

我知道这是一篇旧文章,但是我已经在脚本中使用了它.

I know this is an old post, but I have used this in my scripts.

我不确定它是否正确使用,但是George提出的System.Timers.Timer给了我一个主意,并且似乎对我有用.

I am not sure if its the correct use of it, but the System.Timers.Timer that George put up gave me an idea and it seems to be working for me.

我将它用于有时挂在WMI查询上的服务器,超时会阻止它卡住. 然后,我将消息输出到日志文件中,而不是写主机,以便我可以查看损坏的服务器并在需要时进行修复.

I use it for servers that sometimes hang on a WMI query, the timeout stops it getting stuck. Instead of write-host I then output the message to a log file so I can see which servers are broken and fix them if needed.

我也不使用服务器主机名的Guid.

I also don't use a guid I use the servers hostname.

我希望这有道理并能为您提供帮助.

I hope this makes sense and helps you.

$MyScript = {
              Get-WmiObject -ComputerName MyComputer -Class win32_operatingsystem
            }

$JobGUID = [system.Guid]::NewGuid()

$elapsedEventHandler = {
    param ([System.Object]$sender, [System.Timers.ElapsedEventArgs]$e)

    ($sender -as [System.Timers.Timer]).Stop()
    Unregister-Event -SourceIdentifier $JobGUID
    Write-Host "Job $JobGUID removed by force as it exceeded timeout!"
    Get-Job -Name $JobGUID | Remove-Job -Force
}

$timer = New-Object System.Timers.Timer -ArgumentList 3000 #just change the timeout here
Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action $elapsedEventHandler -SourceIdentifier $JobGUID
$timer.Start()

Start-Job -ScriptBlock $MyScript -Name $JobGUID