在Linux上,有timeout
命令,它有一个非常好的和简单的语法:超时等同于Windows
timeout 120 command [args]
很简单。如果命令运行超过时间限制,它将运行命令并杀死它。尽管我尽了最大的努力,windows上的“解决方案”是多行的,不会将命令的输出显示给终端,如果我将超时时间增加到超过一分钟,cygwin“超时”无法终止进程对此没有解释)。有没有人有更好的主意?
在Linux上,有timeout
命令,它有一个非常好的和简单的语法:超时等同于Windows
timeout 120 command [args]
很简单。如果命令运行超过时间限制,它将运行命令并杀死它。尽管我尽了最大的努力,windows上的“解决方案”是多行的,不会将命令的输出显示给终端,如果我将超时时间增加到超过一分钟,cygwin“超时”无法终止进程对此没有解释)。有没有人有更好的主意?
我的意思是有timeout.exe
,但我不认为这给你很多相同的功能,你正在寻找。我不知道timeout
等效于Windows。根据linked answer中的建议,PowerShell作业将提供有关如何复制timeout
的行为的建议。我推出了一个简单的示例函数
function timeout{
param(
[int]$Seconds,
[scriptblock]$Scriptblock,
[string[]]$Arguments
)
# Get a time stamp of before we run the job
$now = Get-Date
# Execute the scriptblock as a job
$theJob = Start-Job -Name Timeout -ScriptBlock $Scriptblock -ArgumentList $Arguments
while($theJob.State -eq "Running"){
# Display any output gathered so far.
$theJob | Receive-Job
# Check if we have exceeded the timeout.
if(((Get-Date) - $now).TotalSeconds -gt $Seconds){
Write-Warning "Task has exceeded it allotted running time of $Seconds second(s)."
Remove-Job -Job $theJob -Force
}
}
# Job has completed natually
$theJob | Remove-Job -ErrorAction SilentlyContinue
}
这会启动一个作业并不断检查其输出。所以你应该接近运行过程的实时更新。您不必使用-ScriptBlock
,并可以选择基于-Command
的工作。我将使用上面的函数和一个脚本块来展示一个示例。
timeout 5 {param($e,$o)1..10|ForEach-Object{if($_%2){"$_`: $e"}else{"$_`: $o"};sleep -Seconds 1}} "OdD","eVeN"
这将打印数字1到10以及数字均匀度。在显示数字之间会有1秒的停顿。如果达到超时,则会显示警告。在上面的例子中,所有的10号码都不会显示,因为这个过程只允许5秒。
功能可能会使用一些触摸和可能有人在那里,可能已经做到这一点。至少我承认它。
[添加超时到批处理/ powershell]可能重复(https://stackoverflow.com/questions/21176487/adding-a-timeout-to-batch-powershell) –
该链接的解决方案不显示输出到正在运行的屏幕。 – xaav
你可以像'for/f“标记= 3 delims =;”%I in('wmic process call create“ping localhost -n 10”^ | find“ProcessId”')do> NUL(timeout/t 5/nobreak && taskkill/im%I)'在cmd控制台中,或者双击bat脚本中的'%%'。如果你把它放在一个蝙蝠脚本中,你可以把它放在一个函数中,然后调用这个函数。如果控制台,你可以设置一个'doskey'宏。 – rojo