如何检查应用程序是否从批处理(好cmd)文件运行?
如果程序已经在运行,我不需要启动另一个实例。(我不能改变应用程序,使它只有单一实例。)
此外,应用程序可以作为任何用户运行。
如何检查应用程序是否从批处理(好cmd)文件运行?
如果程序已经在运行,我不需要启动另一个实例。(我不能改变应用程序,使它只有单一实例。)
此外,应用程序可以作为任何用户运行。
当前回答
值得一提的是,如果你的任务名称非常长,那么它将不会完整地出现在任务列表结果中,所以它可能会更安全(而不是本地化)。
这个答案的变体:
:: in case your task name is really long, check for the 'opposite' and find the message when it's not there
tasklist /fi "imagename eq yourreallylongtasknamethatwontfitinthelist.exe" 2>NUL | find /I /N "no tasks are running">NUL
if "%errorlevel%"=="0" (
echo Task Found
) else (
echo Not Found Task
)
其他回答
npocmaka使用QPROCESS代替TASKLIST的建议很好,但是,它的答案太大太复杂了,我觉得有义务发布一个相当简化的版本,我想,这将解决大多数非高级用户的问题:
QPROCESS "myprocess.exe">NUL
IF %ERRORLEVEL% EQU 0 ECHO "Process running"
上面的代码是在Windows 7中测试的,用户具有管理员权限。
我提出的另一种可能,不需要保存文件,灵感来自于使用grep:
tasklist /fi "ImageName eq MyApp.exe" /fo csv 2>NUL | find /I "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" echo Program is running
/fi ""定义了一个应用程序的过滤器,在我们的例子中,它是*.exe名称 CSV定义了输出格式,CSV是必需的,因为默认情况下,如果可执行文件的名称太长,它可能会被截断,从而无法被稍后的find匹配。 find /I表示不区分大小写的匹配,可以省略
有关整个语法,请参阅tasklist命令的手册页。
我需要一个重试的解决方案。这段代码将一直运行,直到找到进程,然后将其终止。你可以设置一个超时或任何你喜欢的东西。
注:
“。exe”是必选项 你可以让一个文件运行参数,版本如下
:: Set programm you want to kill
:: Fileextension is mandatory
SET KillProg=explorer.exe
:: Set waiting time between 2 requests in seconds
SET /A "_wait=3"
:ProcessNotFound
tasklist /NH /FI "IMAGENAME eq %KillProg%" | FIND /I "%KillProg%"
IF "%ERRORLEVEL%"=="0" (
TASKKILL.EXE /F /T /IM %KillProg%
) ELSE (
timeout /t %_wait%
GOTO :ProcessNotFound
)
taskkill.bat:
:: Get program name from argumentlist
IF NOT "%~1"=="" (
SET "KillProg=%~1"
) ELSE (
ECHO Usage: "%~nx0" ProgramToKill.exe & EXIT /B
)
:: Set waiting time between 2 requests in seconds
SET /A "_wait=3"
:ProcessNotFound
tasklist /NH /FI "IMAGENAME eq %KillProg%" | FIND /I "%KillProg%"
IF "%ERRORLEVEL%"=="0" (
TASKKILL.EXE /F /T /IM %KillProg%
) ELSE (
timeout /t %_wait%
GOTO :ProcessNotFound
)
使用。\taskkill.bat ProgramToKill.exe运行
如果你有多个同名的。exe文件,你只想检查其中一个(例如,你关心的是C:\MyProject\bin\release\MyApplication.exe而不是C:\MyProject\bin\debug\MyApplication.exe),那么你可以使用以下方法:
@echo off
set "workdir=C:\MyProject\bin\release"
set "workdir=%workdir:\=\\%"
setlocal enableDelayedExpansion
for /f "usebackq tokens=* delims=" %%a in (`
wmic process where 'CommandLine like "%%!workdir!%%" and not CommandLine like "%%RuntimeBroker%%"' get CommandLine^,ProcessId /format:value
`) do (
for /f "tokens=* delims=" %%G in ("%%a") do (
if "%%G" neq "" (
rem echo %%G
set "%%G"
rem echo !ProcessId!
goto :TheApplicationIsRunning
)
)
)
echo The application is not running
exit /B
:TheApplicationIsRunning
echo The application is running
exit /B
我通常在cmd提示符下执行以下命令来检查我的program.exe是否正在运行:
tasklist | grep program