How to use tasklist command with an array? - windows

I'm working on a cmd script and want to find some processes in the tasklist. So what I have is an array like "prog[0]=devcpp.exe, prog[1]=notepad.exe..."
And to find these processes I'm using FOR command. Ok, but when I execute the command "tasklist /fi" it seems won't recognize the array, and don't give me the expected result.
The code is:
set prog[0]=devcpp.exe
set prog[1]=notepad.exe
set prog[2]=calc.exe
FOR /l %%a IN (0,1,2) DO (
tasklist /fi "IMAGENAME eq %prog[%%a]%"
)
But the result is:
error: the search filter cannot be recognized
And of course I am running these processes...
So, any suggestions?

First, remove the trailing QUOTATION MARK character on the prog[2] setting.
Secondly, when invoking tasklist, the PERCENT character must be doubled to retain one. And, use the command line interpreter. %ComSpec%, to interpret the variable.
set prog[0]=devcpp.exe
set prog[1]=notepad.exe
set prog[2]=powershell.exe
FOR /l %%a IN (0,1,2) DO (
"%ComSpec%" /C tasklist /fi "IMAGENAME eq %%prog[%%a]%%"
)
You have given no clue as to what the end goal is about. It would likely be easier to code this in PowerShell as #Bill_Stewart suggested.

Here is my suggestion for this task with a commented batch file.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Delete all environment variables of which name starts with prog[.
for /F "delims==" %%I in ('set prog[ 2^>nul') do set "%%I="
rem Define environment variables with the executables to get listed.
set "prog[0]=devcpp.exe"
set "prog[1]=notepad.exe"
set "prog[2]=calc.exe"
rem Run TASKLIST in a loop to get output a list of those processes
rem from the list defined above which are currently running with the
rem header output on English Windows just on first running process.
set "Header=1"
for /F "tokens=1* delims==" %%I in ('set prog[') do if defined Header (
%SystemRoot%\System32\tasklist.exe /FI "IMAGENAME eq %%J" 2>&1 | %SystemRoot%\System32\findstr.exe /B /I /L /V /C:"INFO:"
if not errorlevel 1 set "Header="
) else (
%SystemRoot%\System32\tasklist.exe /NH /FI "IMAGENAME eq %%J" 2>nul
)
endlocal
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
echo /?
endlocal /?
findstr /?
for /?
if /?
rem /?
set /?
setlocal /?
tasklist /?

Related

Remove comma from variable in CMD

How are you all doing?
I made a batch file that gets the memory usage of a process that has a specific PID...
Here is the code:
#Echo off
REM Get memory from process using tasklist
for /f "tokens=2 delims=," %A in ('tasklist /svc /fi "SERVICES eq .Service02" /FO csv /NH') do (
REM Store PID on a variable
#Set "pidSlv02=%~A"
REM Get memory usage from process with that PID
for /f "tokens=5 delims= " %B in ('tasklist /fi "pid eq %pidSlv02%" /NH') do (
REM Store mem value on another variable
#Set "memSlv02=%~B"
REM Remove commas from variable
#Echo %memSlv02% K
)
)
So, the output is:
1,407,356
Now, i need to convert that number to be 1407356
I did not come here directly. I already tried a couple of things but without success.
Im still very new and learning CMD/batch scripts... Didnt even know t was possible to do so much on Windows. Thought it was only possible on Linux. So please don't be angry with me if i dont understand something. Im trying my best! 😣
Also, sorry if i mispelled something here since this is not my native language.
I tried adding the code:
set memSlv02=!memSlv02:,=!
set /a total=!total! + !memSlv02!
But if i use echo %total% i receive Missing operator. 0
Any tips?
Here's is an example which should output the data you require using the commands you've decided are best for you!
#Echo Off & SetLocal EnableExtensions DisableDelayedExpansion
Set "SvcName=.Service02"
For /F Tokens^=3^ Delims^=^" %%G In ('%SystemRoot%\System32\tasklist.exe
/Fi "Services Eq %SvcName%" /Fo CSV /NH /Svc 2^>NUL') Do Set "PID=%%G"^
& For /F Tokens^=9^ Delims^=^" %%H In ('%SystemRoot%\System32\tasklist.exe
/Fi "PID Eq %%G" /Fo CSV /NH 2^>NUL') Do Set "MemKB=%%H"^
& SetLocal EnableDelayedExpansion & For /F %%I In ("!MemKB:,=!") Do EndLocal^
& Set "MemKB=%%I"
Echo %%SvcName%% = %SvcName%, %%PID%% = %PID%, %%MemKB%% = %MemKB% & Pause
You would obviously replace the last line which I've included just to show you the defined variables. I have made it simple to just replace the Service Name on line two, should you wish to do so, but nothing else should be modified at all.
BTW, I will not be explaining how any of the above works, so I advise that you perform further reasearch should you feel the need to understand it, but cannot currently do so.

How do query and then kill a service in a batch file (newbie)

I am trying to kill specific services using the PID from "SC QUERYEX wuauserv". But I don't know how to pull the PID shown in the results to then run "taskkill /pid /f [PID]". I am trying to make a batch file which I can use on multiple machines remotely.
I have tried a couple of suggestions made in other similar questions found on google, but wuauserv is not being killed for some reason.
# echo off
cmd /c FOR /F "usebackq tokens=2 skip=3" %%i IN (tasklist /fi "services eq wuauserv") DO taskkill /PID %%
pause
The above is what I have, but it's not finding the specific service in the task list. Can anyone assist?
Essentially, because you specified usebackq you need to put your Command within backticks ie: IN (`Command`) DO () you also need to include the variable letter you specified earlier in the ending section which you have, right now it is just %% given you set up i as the variable letter it should be %%i.
Also the CMD /C portion is just not needed at all.
Thats said, just drop the UseBackQ it isn't necessary, here is yoru code cleaned up a little.
#(
SETLOCAL EnableDelayedExpansion
echo off
)
FOR /F "Tokens=2" %%I IN ('
Tasklist /fi "Services eq wuauserv"
^| FIND /I "wuauserv"
') DO (
ECHO Killing PID %%I
Taskkill /PID %%I
)
PAUSE

Batch error "( unexpected" if statement nested inside for loop

I wrote this small script to kill Spotify whenever the title of the window is "Advertisement". For now, it just looks for the spotify.exe process and, if the name of the window matches, kills it (next step is executing it every second). However, I get an error every time I execute it, telling me that there's an unexpected ( in IF /i "%A:~0,4" (, but such statement is not in my code: it seems like Windows modifies IF /i "%%A:~0,4%"=="PID:" ( before executing it.
Here's the script:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
tasklist /fi "imagename eq spotify.exe" /fo list /v > tmp.txt
FOR /F "usebackq tokens=*" %%A IN ("tmp.txt") DO (
SET test=%%A
echo %%A
IF /i "%%A:~0,4%"=="PID:" (
SET "pid=%%A:PID: =%"
echo %pid%
)
IF /i "%%A:~0,13%"=="Window Title:" (
SET "wintitle=%%A:Window Title: =%"
echo %wintitle%
)
IF "%wintitle%"=="Advertisement" (
taskkill /F /PID %pid%
)
)
PAUSE
Error message (with echo on):
C:\Users\marco\Desktop>antispotify.bat
C:\Users\marco\Desktop>tasklist /fi "imagename eq spotify.exe" /fo list /v 1>tmp.txt
( was unexpected at this time.
C:\Users\marco\Desktop> IF /i "%A:~0,4" (
Does anyone know what's wrong with my code?
The task to force a real kill of Spotify process running for advertisement can be done also by using following batch file without using delayed expansion.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\tasklist.exe /FI "imagename eq spotify.exe" /FO LIST /V 2^>nul') do (
if /I "%%~I" == "PID" (
for /F %%K in ("%%~J") do set "ProcessIdentifier=%%~K"
) else if /I "%%~I" == "Window Title" (
for /F "tokens=*" %%K in ("%%~J") do if /I "%%~K" == "Advertisement" call %SystemRoot%\System32\taskkill.exe /F /PID %%ProcessIdentifier%%
)
)
endlocal
The same code with using delayed environment variable expansion:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\tasklist.exe /FI "imagename eq spotify.exe" /FO LIST /V 2^>nul') do (
if /I "%%~I" == "PID" (
for /F %%K in ("%%~J") do set "ProcessIdentifier=%%~K"
) else if /I "%%~I" == "Window Title" (
for /F "tokens=*" %%K in ("%%~J") do if /I "%%~K" == "Advertisement" %SystemRoot%\System32\taskkill.exe /F /PID !ProcessIdentifier!
)
)
endlocal
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
echo /?
endlocal /?
for /?
if /?
setlocal /?
taskkill /?
tasklist /?
See also: How does the Windows Command Interpreter (CMD.EXE) parse scripts?
As noted in the comments, substring manipulation doesn't work on for variables (%%a type). Instead, you need an ordinary variable and of course delayed expansion.
But may I suggest another approach:
#ECHO OFF
SETLOCAL
for /f "tokens=2,9 delims=," %%a in ('tasklist /fi "imagename eq notepad.exe" /fo csv /v /nh') do (
set "pid=%%~a"
set "wintitle=%%~b"
)
set pid
set wintitle
IF "%wintitle%"=="Advertisement" taskkill /F /PID %pid%
Here we use the command directly with the for loop instead of using a temporary file. Besides that, we change the output format to csv (easier to parse) with no header line ( /nh)
( I used notepad.exe, because I don't have spotify, but that's easy to adapt)

Batch - echo is off issue

I've checked other tons of answers related to my issue and none worked. I suppose it's a syntax typo, but I cannot seem to find it.
My script should simply tell me if a process is running, then save the path into a variable, go to that path and delete the .exe.
Unfortunately, I get ECHO is OFF. Any ideas why?
#echo off
setlocal EnableDelayedExpansion
set /p PROGRAM=NAme of the exe:
tasklist /FI "IMAGENAME eq %PROGRAM%" 2>NUL | find /I /N "%PROGRAM%">NUL
if "%ERRORLEVEL%"=="0" echo. %PROGRAM% is running
for %%i in (%PROGRAM%) do (
echo %%~$PATH:i
set PROGRAM_PATH=%%~$PATH:i
)
cd %PROGRAM_PATH%
del /F %PROGRAM_PATH%
pause
So, I realized that my program wasn't doing what I wanted because the .exe didn't exist.
So, I modified a little bit the script, so that I will handle that case:
if the .exe is running, exit because I won't be able to delete a already in use .exe anyway;
otherwise go to its location and delete it.
My final program:
#echo off
setlocal EnableDelayedExpansion
goto start_program
:start_program
set /p PROGRAM=Name of exe(ex:cmd.exe):
tasklist /FI "IMAGENAME eq %PROGRAM%" 2>NUL | find /I /N "%PROGRAM%">NUL
if "%ERRORLEVEL%"=="0" do (
goto enter_program
)
if "%ERRORLEVEL%"=="1" do (
goto exit_program
)
:enter_program
for %%i in (%PROGRAM%) do (
set PROGRAM_PATH=%%~$PATH:i
)
cd %PROGRAM_PATH%
del /f %PROGRAM_PATH%
goto:eof
:exit_program
goto:eof
Thanks for tips Ryan and jeb

How to identify IMAGENAME with spaces in a batch file (tasklist)?

Right now, I'm writing a batch file with a line that is identifying if a process is running from my process list.
The line I'm referring to:
FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq %EXE%"') DO IF %%x == %EXE% goto ProcessFound
EXE is defined beforehand as EXE= My Process Here.exe
My batch file works with normal processes, but as you can see with My Process Here.exe, there is a space between My and Process and Here.exe and this is not recognizable.
Is there any way to fix this? The process I am looking for has spaces and I can't change the process name as the program it is related to will not run if I do.
Thanks.
#ECHO OFF
SETLOCAL
SET "exe=7+ Taskbar Tweaker.exe"
FOR /F %%x IN ('tasklist ^|FINDSTR /i /b /L /c:"%EXE%"') DO IF NOT ERRORLEVEL 1 goto ProcessFound1
ECHO "%exe%" not found
GOTO again
:Processfound1
ECHO "%exe%" found!
:again
SET "exe=I dont exist.exe"
FOR /F %%x IN ('tasklist ^|FINDSTR /i /b /L /c:"%EXE%"') DO IF NOT ERRORLEVEL 1 goto ProcessFound1
ECHO "%exe%" not found
GOTO :eof
:Processfound2
ECHO "%exe%" found!
GOTO :EOF
This may work for you. You'd need to fix the process names of course.
#echo off
setlocal enableextensions disabledelayedexpansion
set "exe=My Process Here.exe"
set "processFound="
for /f "tokens=5 delims=," %%a in ('
tasklist /fi "imagename eq %exe%" /fo:csv /nh
') do set "processFound=1"
if defined processFound (
echo %exe% is running
) else (
echo %exe% is NOT running
)
The tasklist will retrieve the list of processes for for the indicated image name and in csv format, without headers.
There are two options: the process is not running and then there are not csv records in the output, or the process is running and there are csv records in the ouptut.
The for command will try to tokenize the output of tasklist and retrieve the 5th token in the line using commas as delimiters.
If the output from tasklist is a csv record, this token will exist, the replaceable parameter will get data and the code in the do clause will be executed. If the output is not a csv record, the token will not exist, and the code in the do clause will not be executed.
Neither of the prior answers worked for me for identifying imagenames with embedded spaces. What did work for me was to use "delims=tab" where tab is the actual tab character as in:
FOR /F "delims=tab" %%X IN ('tasklist /NH /FI "IMAGENAME eq !EXE!"') DO (...
The resulting %%X will either be the entire tasklist entry corresponding to the !EXE! imagename, if found, or "INFO: No tasks are running which match the specified criteria", if not found, that can be acted on by something like:
SET TASKLINE=%%X
IF "!TASKLINE!"=="!TASKLINE:No tasks are running=!" (
ECHO !EXE! FOUND IN !TASKLINE!
) ELSE (
ECHO !EXE! NOT FOUND IN !TASKLINE!))

Resources