如何检查应用程序是否从批处理(好cmd)文件运行?

如果程序已经在运行,我不需要启动另一个实例。(我不能改变应用程序,使它只有单一实例。)

此外,应用程序可以作为任何用户运行。


当前回答

TASKLIST | FINDSTR ProgramName || START "" "Path\ProgramName.exe"

其他回答

TrueY的回答似乎是最优雅的解决方案,然而,我不得不瞎折腾一番,因为我不明白到底发生了什么。我先把问题讲清楚希望能给下一位同学节省点时间。

TrueY修改后的答案:

::Change the name of notepad.exe to the process .exe that you're trying to track
::Process names are CASE SENSITIVE, so notepad.exe works but Notepad.exe does NOT
::Do not change IMAGENAME
::You can Copy and Paste this into an empty batch file and change the name of
::notepad.exe to the process you'd like to track
::Also, some large programs take a while to no longer show as not running, so
::give this batch a few seconds timer to avoid a false result!!

@echo off
SETLOCAL EnableExtensions

set EXE=notepad.exe

FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq %EXE%"') DO IF %%x == %EXE% goto ProcessFound

goto ProcessNotFound

:ProcessFound

echo %EXE% is running
goto END
:ProcessNotFound
echo %EXE% is not running
goto END
:END
echo Finished!

不管怎样,我希望这对你们有帮助。我知道,如果你像我一样是新手,阅读批处理/命令行有时会有点困惑。

我提出的另一种可能,不需要保存文件,灵感来自于使用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命令的手册页。

我使用PV.exe从http://www.teamcti.com/pview/prcview.htm安装在程序文件\PV与这样的批处理文件:

@echo off
PATH=%PATH%;%PROGRAMFILES%\PV;%PROGRAMFILES%\YourProgram
PV.EXE YourProgram.exe >nul
if ERRORLEVEL 1 goto Process_NotFound
:Process_Found
echo YourProgram is running
goto END
:Process_NotFound
echo YourProgram is not running
YourProgram.exe
goto END
:END

马特·莱西(Matt Lacey)提供的答案适用于Windows XP。但是,在Windows Server 2003中行

 tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log

返回

信息:没有匹配指定条件的任务正在运行。

然后在进程运行时读取。

我没有大量的批处理脚本编写经验,所以我的解决方案是在search.log文件中搜索进程名,并将结果输入到另一个文件中,然后搜索任何输出。

tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log

FINDSTR notepad.exe search.log > found.log

FOR /F %%A IN (found.log) DO IF %%~zA EQU 0 GOTO end

start notepad.exe

:end

del search.log
del found.log

我希望这能帮助到其他人。

你应该检查父进程名,参见代码项目中关于基于。net解决方案的文章**。

一种非编程的检查方法:

发射用于cmd . exe 启动一个应用程序(例如,c:\windows\notepad.exe) 在进程资源管理器中检查“Notepad.exe”进程的属性 检查父进程(显示cmd.exe)

同样可以通过获取父进程名进行检查。