Remove comma from variable in CMD - windows

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.

Related

How to use tasklist command with an array?

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 /?

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

bat file loop stops too early

I am using this piece of code to run a loop within a list of active processes to identify a process by name to change the priority.
TIMEOUT /T 1
for /F "tokens=1,2" %%i in ('tasklist /FI "IMAGENAME eq java.exe" /fo table /nh') do set pid=%%j
echo %pid%
wmic process where processid=%pid% CALL setpriority 128
exit
My problem is I have more than one process called "java.exe" but I want them all to be effected by my code. How can I achieve this?
for /F "tokens=1,2" %%i in ('tasklist /FI "IMAGENAME eq java.exe" /fo table /nh') do (
echo %%j
wmic process where processid=%%j CALL setpriority 128
)
(untested)
This method will allow you to use the variable pid, but you will need to use delayed expansion.
SETLOCAL ENABLEDELAYEDEXPANSION
for /F "tokens=1,2" %%i in ('tasklist /FI "IMAGENAME eq java.exe" /fo table /nh') do set pid=%%j
echo !pid!
wmic process where processid=!pid! CALL setpriority 128
exit
The setlocal line is to allow cmd to process the variables at run-time, not phrase-time.
! denotes to process the variable at run-time, not phrase-time.

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

How to extract a specific field from output of tasklist on the windows command line

I ran the following command on the windows command prompt
C:>tasklist /fi "Imagename eq BitTorrent.exe"
The output of which is
Image Name PID Session Name Session # Mem Usage
================== ======== ================= =========== =========
BitTorrent.exe 6164 Console 3 24,144K
I need to extract only one field, the PID, i.e. the number 6164 from the above output.
How do I achieve this ?
More generally, how do I extract a subset(1/more) of the fields from the output of a command on the windows command line ?
Similar to previous answers, but uses specific switches in tasklist to skip header and behave correctly irrespective of spaces in image names:
for /f "tokens=2 delims=," %F in ('tasklist /nh /fi "imagename eq BitTorrent.exe" /fo csv') do #echo %~F
(as run directly from cmd line, if run from batch replace %F with %%F
the easiest way is with using WMIC:
c:\>wmic process where caption="BitTorrent.exe" get ProcessId
EDIT: As the WMIC is not part of home editions of windows:
for /f "tokens=1,2 delims= " %A in ('tasklist /fi ^"Imagename eq cmd.exe^" ^| find ^"cmd^"') do echo %B
Here is used CMD of the caption.You can change it in the find and tasklist parameters.
If this used in batch file you'll need %%B and %%A
You can use wmic command to not filter the output:
wmic process where name="BitTorrent.exe" get processid | MORE +1
UPDATE: Another way:
#Echo OFF
FOR /F "tokens=2" %%# in ('tasklist /fi "Imagename eq winamp.exe" ^| MORE +3') do (Echo %%#)
Pause&Exit
PS: Remember you need to set right the tokens if the app filename contain spaces.

Resources