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

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

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


当前回答

以下是我的解决方法:

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

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

start notepad.exe

:end

del search.log

如果记事本没有运行,上面的操作将打开记事本。

编辑:注意这不会发现隐藏在任务列表中的应用程序。这将包括以不同用户运行的任何计划任务,因为这些任务将自动隐藏。

其他回答

我假设这里是窗户。因此,您需要使用WMI来获取该信息。查看脚本编写者的档案,有很多关于如何从脚本中使用WMI的示例。

我不知道如何用内置CMD这样做,但如果你有grep,你可以尝试以下:

tasklist /FI "IMAGENAME eq myApp.exe" | grep myApp.exe
if ERRORLEVEL 1 echo "myApp is not running"

我提出的另一种可能,不需要保存文件,灵感来自于使用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文件,你只想检查其中一个(例如,你关心的是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

我使用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