Search code examples
windowsbatch-filecmdpidtasklist

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?


Solution

  • 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.