如何设置运行PowerShell脚本的时间限制? [英] How can you set a time limit for a PowerShell script to run for?

查看:865
本文介绍了如何设置运行PowerShell脚本的时间限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在PowerShell(v2)脚本上设置时间限制,以便在该时间限制到期后强制退出.

I want to set a time limit on a PowerShell (v2) script so it forcibly exits after that time limit has expired.

我在PHP中看到它们具有诸如set_time_limit和max_execution_time之类的命令,您可以在其中限制脚本甚至函数执行的时间.

I see in PHP they have commands like set_time_limit and max_execution_time where you can limit how long the script and even a function can execute for.

对于我的脚本,正在查看时间的do/while循环是不合适的,因为我正在调用可能会长时间挂起的外部代码库.

With my script, a do/while loop that is looking at the time isn't appropriate as I am calling an external code library that can just hang for a long time.

我想限制一段代码,只允许它运行x秒钟,之后我将终止该代码块,并向用户返回脚本超时的响应.

I want to limit a block of code and only allow it to run for x seconds, after which I will terminate that code block and return a response to the user that the script timed out.

我看过后台作业,但是它们在不同的线程中运行,因此不会对父线程拥有杀死权限.

I have looked at background jobs but they operate in a different thread so won't have kill rights over the parent thread.

有人处理过这个问题或有解决方案吗?

Has anyone dealt with this or have a solution?

谢谢!

推荐答案

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

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

这篇关于如何设置运行PowerShell脚本的时间限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆