0

我正在尝试编写一个批处理程序,该程序将监视 cpu 使用情况并在 cpu 使用率高时停止病毒扫描。然后,当 CPU 使用率下降时,它将重新开始扫描。

ECHO Checks if the total CPU usage is greater than 10%

SET scanEnd=0

tasklist /FI "IMAGENAME eq scan32.exe" 2>NUL | find /I /N "scan32.exe">NUL
IF "%ERRORLEVEL%"=="0" (
ECHO Program is running

wmic cpu get loadpercentage /value
FOR /f "tokens=2-3 delims==" %%b in ('wmic cpu get loadpercentage /value') do (
echo %%b >> tempfile.txt
echo removed %%a)

SET /a load < tempfile.txt
DEL tempfile.txt
ECHO Load is "%load%"

IF load GEQ 10 (
ECHO High cpu usage
TSKILL scan32
SET scanEnd=1
))
PAUSE

IF "1" == "%scanEnd%" (
ECHO Scan not finished
IF load LSS 10 (
ECHO Restarting scan
"C:\Program Files\McAfee\VirusScan Enterprise\scan32.exe"
SET scanEnd=0))
ECHO End of program
PAUSE

wmic 以 LoadPercentage=0(或其他数字)的形式返回 CPU 使用率。我用 for 循环过滤它并分配要加载的数字。由于我不明白的原因,作业有问题。我无法回显该值(显示“”),并且无论我如何定义高 CPU 使用率,负载都会通过 IF GEQ 语句。即使是 0% 的负载显然也大于 10。我知道问题出在 set 上,因为我检查了 tempfile.txt 并且它被正确过滤,但我仍然不知道为什么它是错误的。

谢谢你的帮助。

4

1 回答 1

0

you assumed that SET command can read from stdin which is not the case.

You might simply assign the FOR variable into a new variable.

Try this

for /f "tokens=2-3 delims==" %%a in ('wmic cpu get loadpercentage /value') do (
  set /a load=%%a
)

and then

if %load% geq 10 (
  echo load greater than 10%
)

but beware of the assignments inside FOR loops. You may need to enable delayed expansion for them to work correctly, in case there are more than one assignment in the loop. Eventhough this is not your case, you'd just need to adjust

setlocal enabledelayedexpansion

and then refer to it using this optional syntax

if !load! geq 10 (
于 2012-07-25T16:33:12.067 回答