Home > other >  Batch: find a Task Name that starts with
Batch: find a Task Name that starts with

Time:12-23

tasklist | find /I "ABC" 
if errorlevel 1 (
   REM Do Something
) ELSE (
   REM Do Nothing
)

I am trying to find a way to find a task that starts with "ABC" so if multiple tasks with a similar name are running it will trigger if there are 1 or more.

CodePudding user response:

You can check for 1 more tasks and execute as follows:

for /f "delims=" %%g in (' %__APPDIR__%tasklist.exe ^| %__APPDIR__%findstr.exe /i "\<ABC" ^| %__APPDIR__%find.exe /c /v ""') do set "_taskCount=%%g"
if "%_taskCount%" GEQ "1" (
REM Replace the echo line with whatever you wish to do.
echo 1 or more listed.
) else (
REM Replace the echo line with whatever you wish to do.
echo Zero are listed.
)

Edit: Some quick explanations:

find.exe /c /v "" With this you are searching the count with /c and with /v "" you are searching for all lines which aren't blank. See Find

GEQ means Greater Than or Equal to. Since you want instances of one or more tasks. See the If command.

You can also type the following in the command prompt:

findstr /?
find /?
if /?

Edit 2: As per Compo's comments, this can be simplified if you do not need the count of the items found with the following:

%__APPDIR__%tasklist.exe | %__APPDIR__%findstr.exe /i "\<ABC" > nul
if not errorlevel 1 (
REM Do what you want if the item is found.
echo 1 or more found
) else (
REM Do what you want if no items are found.
echo No items found
)

This will check if any item matches the search. If the errorlevel is not 1, then an item matched. If it is 1, then no item matched.

  • Related