如何检查应用程序是否从批处理(好cmd)文件运行?
如果程序已经在运行,我不需要启动另一个实例。(我不能改变应用程序,使它只有单一实例。)
此外,应用程序可以作为任何用户运行。
如何检查应用程序是否从批处理(好cmd)文件运行?
如果程序已经在运行,我不需要启动另一个实例。(我不能改变应用程序,使它只有单一实例。)
此外,应用程序可以作为任何用户运行。
当前回答
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!
不管怎样,我希望这对你们有帮助。我知道,如果你像我一样是新手,阅读批处理/命令行有时会有点困惑。
其他回答
在Windows下,您可以使用Windows管理规范(WMI)来确保没有带有指定命令行的应用程序被启动,例如:
Wmic进程where (name="nmake.exe") get commandline | findstr /i /c:"/f load. exe"Mak“/c:”/f build。编译已经开始了!> %ALREADY_STARTED & exit /b 1)
我使用了Matt提供的脚本。我唯一遇到的麻烦是它不能删除search.log文件。我想是因为我必须cd到另一个位置来启动我的程序。我cd回BAT文件和search.log所在的位置,但它仍然不能删除。所以我首先删除了search.log文件,而不是最后删除。
del search.log
tasklist /FI "IMAGENAME eq myprog.exe" /FO CSV > search.log
FOR /F %%A IN (search.log) DO IF %%-zA EQU 0 GOTO end
cd "C:\Program Files\MyLoc\bin"
myprog.exe myuser mypwd
:end
如果你有多个同名的。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
基于vtrz的回答和Samuel Renkert关于另一个主题的回答,我想出了以下脚本,如果它还没有运行,则只运行%EXEC_CMD%:
@echo off
set EXEC_CMD="rsync.exe"
wmic process where (name=%EXEC_CMD%) get commandline | findstr /i %EXEC_CMD%> NUL
if errorlevel 1 (
%EXEC_CMD% ...
) else (
@echo not starting %EXEC_CMD%: already running.
)
如前所述,这需要管理特权。
我假设这里是窗户。因此,您需要使用WMI来获取该信息。查看脚本编写者的档案,有很多关于如何从脚本中使用WMI的示例。