如何检查应用程序是否从批处理(好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中测试的,用户具有管理员权限。
我使用了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
值得一提的是,如果你的任务名称非常长,那么它将不会完整地出现在任务列表结果中,所以它可能会更安全(而不是本地化)。
这个答案的变体:
:: 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
)
马特·莱西(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
我希望这能帮助到其他人。
如果你有多个同名的。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