TAGS :Viewed: 3 - Published at: a few seconds ago

[ BATCH Alert user to low system memory or disk space ]

Having tried variations of the following, and with further additional code, what is wrong here? Thanks!

@echo off
goto checkmemorystatus
:checkmemorystatus
for /f "skip=1" %%p in ('wmic os get freephysicalmemory') do ( 

set m=%%p
if %m% LSS <threshold> (start echo FREE RAM ALERT: %m% & PING 1.1.1.1 -n 1 -w 60000 >NUL)
  goto checkmemorystatus
)

Answer 1


no need for delayed expansion (as there is no need for an additional variable):

@echo off
:checkmemorystatus
PING localhost -n 2 -w 60000 >NUL
for /f "skip=1" %%p in ('wmic os get freephysicalmemory') do ( 
   if %%p leq 700000 ( echo FREE RAM ALERT: %%p ) else (echo FREE RAM ok   : %%p)
   goto checkmemorystatus
)

(the code is basically taken from mihai_mandis) wmic gives you more lines than you want. You already ignored the first line with skip. The above code breaks the for-loop after one run and to ignore the following lines. ( I added a "Free RAM ok" for testing purposes - you may want to delete it)

Answer 2


  1. At the beginning of the script set delayed expansion:

    setlocal EnableDelayedExpansion

This will allow you to access variables in for loops in format !var_name!

2.Do not use goto statements inside for block. This will cause for break.

   @echo off
    setlocal EnableDelayedExpansion
    :checkmemorystatus

    for /f "skip=1" %%p in ('wmic os get freephysicalmemory') do ( 
       set mm=%%p
       if !mm! LSS <threshold> (
          start echo FREE RAM ALERT: !mm!
          PING localhost -n 1 -w 60000 >NUL
       )
    )
goto :checkmemorystatus