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

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

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


当前回答

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

其他回答

基于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.
)

如前所述,这需要管理特权。

在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)

值得一提的是,如果你的任务名称非常长,那么它将不会完整地出现在任务列表结果中,所以它可能会更安全(而不是本地化)。

这个答案的变体:

:: 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
)

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

如果你有多个同名的。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