Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
windows的等效超时_Windows_Powershell_Batch File - Fatal编程技术网

windows的等效超时

windows的等效超时,windows,powershell,batch-file,Windows,Powershell,Batch File,在linux上,有timeout命令,它有一个非常好且简单的语法: timeout 120 command [args] 很简单。它运行该命令,并在命令运行超过时间限制时终止该命令。尽管我尽了最大努力,windows上的“解决方案”是多行的,不会显示到终端的命令输出,如果我将超时增加到一分钟以上,cygwin“timeout”也无法终止进程(对此我没有解释)。有人有更好的主意吗?我的意思是有,但我认为这并没有给你提供你想要的功能 我不知道Windows是否有超时等价物。按照PowerShell

在linux上,有
timeout
命令,它有一个非常好且简单的语法:

timeout 120 command [args]
很简单。它运行该命令,并在命令运行超过时间限制时终止该命令。尽管我尽了最大努力,windows上的“解决方案”是多行的,不会显示到终端的命令输出,如果我将超时增加到一分钟以上,cygwin“timeout”也无法终止进程(对此我没有解释)。有人有更好的主意吗?

我的意思是有,但我认为这并没有给你提供你想要的功能

我不知道Windows是否有
超时
等价物。按照PowerShell作业中的建议,将有一个关于如何复制
timeout
s行为的建议。我推出了一个简单的示例函数

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秒


功能可能需要一些润色,可能有人已经做过了。至少我能接受

链接解决方案的可能副本在运行时不会在屏幕上显示输出。您可以在cmd控制台中执行类似以下操作:
for/f“tokens=3 delims=;%I in('wmic进程调用create“ping localhost-n 10”^ find“ProcessId”')do>NUL(timeout/t5/nobreak&&taskkill/im%I)
,或者将bat脚本中的
%%
加倍。如果你把它放在一个bat脚本中,你可以把它放在一个函数中,然后调用这个函数。如果是控制台,您可以设置一个
doskey
宏。@rojo这几乎可以,但是标准输出出现在一个新窗口中。有没有办法在同一个窗口中捕获stdout?@xaav我在考虑使用
start/b
,但是要获得生成的进程的PID,没有简单的方法。您必须执行
taskkill/im“imagename eq ping.exe”
或类似操作,这可能会造成可执行文件在多个并发窗口中运行的不幸后果。而且,如果有必要的话,这会使程序变得非交互式。