我正在编写一个运行一些程序的批处理脚本。当每个程序完成它正在做的事情时,它会等待用户关闭它,继续下一个,或者在超时这么多秒后被 taskkill 关闭。如果我将主脚本视为 MAIN,将程序视为 TASK,将计时器视为 KILLER。MAIN(大约)同时启动 TASK 和 KILLER。TASK 完成了它应该做的事情,KILLER 在杀死 TASK 之前等待 600 秒。但是,如果 TASK 被用户关闭,它应该杀死 KILLER 并在没有用户交互的情况下返回 MAIN。但是,使用 ping 或 timeout 我仍然必须等待计时器到期,然后批次才会真正关闭。我不想让我的桌面上到处都是无用的命令窗口。有没有办法解决?
问问题
1326 次
2 回答
0
你可以使用这样的东西
@echo off
setlocal enableextensions disabledelayedexpansion
start "" task.exe
call :timeoutProcess "task.exe" 300
start "" task.exe
call :timeoutProcess "task.exe" 300
exit /b
:timeoutProcess process timeout [leave]
rem process = name of process to monitor
rem timeout = timeout in seconds to wait for process to end
rem leave = 1 if process should not be killed on timeout
for /l %%t in (1 1 %~2) do (
timeout /t 1 >nul
tasklist | find /i "%~1" >nul || exit /b 0
)
if not "%~3"=="1" taskkill /f /im "%~1" >nul 2>nul
if %errorlevel% equ 128 ( exit /b 0 ) else ( exit /b 1 )
超时逻辑被移动到一个子例程,该子例程将等待直到进程结束或达到超时。
于 2014-10-24T18:57:53.783 回答
0
这是一个vbs脚本。
它等到程序退出,看看它是否是记事本,如果是,则重新启动记事本。更改Win32_ProcessStopTrace
为Win32_ProcessStartTrace
程序启动或Win32_ProcessTrace
所有启动和停止。
控制台脚本是这样启动的。GUI 脚本只是直接执行脚本。GUI 脚本是不可见的。
cscript "c:\somefolder\script.vbs"
在脚本中等待使用wscript.sleep 600000
(毫秒)。
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set objEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM Win32_ProcessStopTrace")
Do
Set objReceivedEvent = objEvents.NextEvent
wscript.echo objReceivedEvent.ProcessName
If lcase(objReceivedEvent.ProcessName) = lcase("Notepad.exe") then
WScript.echo "Process exited with exit code " & objReceivedEvent.ExitStatus
WshShell.Run "c:\Windows\notepad.exe", 1, false
End If
Loop
这就是如何启动一个不可见的命令窗口。
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd /k dir c:\windows\*.*", 0, false
于 2014-10-24T19:45:04.677 回答