How to get the current CPU usage and available memory in batch file?

爷,独闯天下 提交于 2019-12-20 12:47:09

问题


I am creating a simple script that outputs the current user logged in, CPU usage for the current system and the available memory?

I have managed to get the current user/s logged on but is it possible to get the cpu usage and memory as well?

This is my code so far.

@echo off

for /f "tokens=3 delims=\" %%i in ("%USERPROFILE%") do (set USER=%%i) 2>&1  
echo "Logged On User: %USER%"  
echo. 

pause

To get the cpu usage i have tried this command but it doesn't seem to be working.

for /f "skip=1" %p in ('wmic cpu get loadpercentage') do 
echo %p%

回答1:


You could always utilise the systeminfo command, but then would be forced to go through a brief loading screen

set totalMem=
set availableMem=
set usedMem=
REM You need to make a loop
for /f "tokens=4" %%a in ('systeminfo ^| findstr Physical') do if defined totalMem (set availableMem=%%a) else (set totalMem=%%a)
set totalMem=%totalMem:,=%
set availableMem=%availableMem:,=%
set /a usedMem=totalMem-availableMem
Echo Total Memory: %totalMem%
Echo Used Memory: %usedMem%

And that should do exactly what you want. This code can easily be modified to show Virtual Memory as well. (The use of set totalMem=%totalMem:,=% and set availableMem=%availableMem:,=% gets rid of commas in the variables.)

Mona




回答2:


Firstly, when running from a batch file, the for loop variable needs two percentage symbols - %%p

Secondly, you need to echo %%p, not %p%:

for /f "skip=1" %%p in ('wmic cpu get loadpercentage') do echo %%p

From the command line:

for /f "skip=1" %p in ('wmic cpu get loadpercentage') do echo %p



回答3:


typeperf "\processor(_Total)\% Processor Time"  -SC 1 -y

or

C:\>logman create counter CPU_Usage3 -c "\Processor(_Total)\% Processor Time" -f csv -o %temp%\cpu.csv
The command completed successfully.

C:\>logman start CPU_Usage3
The command completed successfully.

C:\>logman stop CPU_Usage3
The command completed successfully.

C:\>type %temp%\cpu*.csv
The system cannot find the file specified.

Typeperf is not available for WindowsXP home ,but logman requires admin privileges and creates a temp file. TYPEPERF . LOGMAN . For the memory check these counters: http://ss64.com/nt/syntax-performance-counters.html




回答4:


@echo off

setlocal enabledelayedexpansion

set Times=0

for /f "skip=1" %%p in ('wmic cpu get loadpercentage') do (

set Cpusage!Times!=%%p

set /A Times=!Times! + 1

)

echo Percentage = %Cpusage0%

pause


来源:https://stackoverflow.com/questions/20208373/how-to-get-the-current-cpu-usage-and-available-memory-in-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!