How to check if a batch already running(support remote desktop, multi-user, multi-session)?
在批处理中,判断当前批处理是否已经运行可以简单的方法是:
在批处理的开头,添加两行代码:
tasklist /fi "windowtitle eq 管理员: Batch_VPN*" 2>nul | find /i "PID" && exit
title Batch_VPN
上面的代码, 有两个问题,一个是用管理员权限运行和不用管理员权限运行会有问题,另外一个就是在多用户和远程桌面的情况下,无法拿到其他用户的windowtitle。
The best, charming, graceful, simply, correct, accuracy way to check if the batch already running or not.
用下面的代码,可以准确判断是否已经运行,如果已经运行,就退出去批处理:
skip 3 because first line is header, the second line be the batch, and the third line be the wmic command
used %~nx0% because %~0 might include \ char, it's an escape char for wmic query string
Code:
@echo off
set /a count=0
for /f "skip=3 USEBACKQ delims=" %%a in (`wmic process where "name='cmd.exe' and commandline like '%%%~nx0%%'" get processid`) do set /a count+=1
if %count% gtr 1 exit
echo 我要运行, Please run me....
pause
题外话,如果要查找某个特定进程是否已经运行(exe),可以用tasklist或者wmic,例如:
tasklist /fi "imagename eq yourapp.exe" | find "yourapp.exe" && exit