Computing Staff
  • 2

Batch File For Loop Increment

  • 2

I’ve got a two part batch file that runs on a system schedule on win2k3 server.

Part 1 uses WMI to get the current load on the system and write to a CSV file every five minutes. – works.

Part 2 takes that CSV file and calculates average load. – fail

My problem is down to incrementing the counter for the lines and adding to the running total for calculating the average. Here’s what I have, but when I run it, TOTALLOAD never has any value other than that last value from the CSV file, and counter is always 0.

@echo off & setlocal enabledelayedexpansion

REM check cmd line args for no or 1 arg
if “%1″==”” goto msg
if “%2″==”” goto setArg

:setArg
set node=%1
goto loopFile

:loopFile

more %node%\cpuload.txt > temp.txt

REM set globals
set /a counter=0
set /a TOTALLOAD=0

for /F “tokens=1,2,3 delims=,” %%m in (‘findstr /v “Node,LoadPercentage,MaxClockSpeed” temp.txt’) do (
set localMachine=%%m
set CPUload=%%n
set CPUspeed=%%o
set /a counter+=1
set /a TOTALLOAD=%TOTALLOAD%+%CPUload%
echo Count is: %counter%
)

REM del temp.txt
echo totalLoad is: %totalLoad%
set /a averageLoad=%totalLoad% / %counter%
echo “%averageLoad%” >> %node%\dailyAverage.txt
REM del %node%\cpuload.txt
goto end

:msg
echo You may specify at one or two computer name(s). Using localhost
set node=%computername%
echo %node%
goto loopFile

:end

Hopefully enough people still use batch files out there that can help me. Thanks

Share

1 Answer

  1. I actually played around with this and got it working by putting in an exclamation point around the variable while inside the for loop. Thanks all for your time. This forum was the only way I got this far!!!

    Here’s the CSV and the numeric CPU load is what I am averaging.
    Node,LoadPercentage,MaxClockSpeed
    batphonevm,21,2200
    Node,LoadPercentage,MaxClockSpeed
    batphonevm,4,2200
    Node,LoadPercentage,MaxClockSpeed
    batphonevm,33,2200
    Node,LoadPercentage,MaxClockSpeed
    batphonevm,24,2200

    And here’s the new for loop so everyone can see.
    REM set globals
    set /a counter=0
    set /a TOTALLOAD=0

    for /F “tokens=1,2,3 delims=,” %%m in (‘findstr /v “Node,LoadPercentage,MaxClockSpeed” temp.txt’) do (
    set localMachine=%%m
    set /a CPUload=%%n
    set /a CPUspeed=%%o
    set /a counter+=1
    set /a TOTALLOAD=!TOTALLOAD!+!CPUload!

    )

    del temp.txt
    echo totalLoad is: %totalLoad%
    set /a averageLoad=%totalLoad% / %counter%
    echo Average load is: %averageLoad%
    echo %date%,%averageLoad% >> %node%\dailyCPUAverage.txt
    REM del %node%\cpuload.txt

    • 0