Windows Batch Script for getting disk space details

batchwindows

I need to get the mail alert for disk space details. I have found this script in our forum. When I run this script in command prompt, it generates the output as mentioned below. But when I run this by saving it as a batch file, it doesn't work.

Can any one help me how to make this as a batch file or any other method to get the disk space details using batch file, so that I could schedule in Task Scheduler.

Script

(for /f "tokens=1-3" %a in ('WMIC LOGICALDISK GET FreeSpace^,Name^,Size ^|FINDSTR /I /V "Name"') do @echo wsh.echo "%b" ^& " free=" ^& FormatNumber^(cdbl^(%a^)/1024/1024/1024, 2^)^& " GB"^& " size=" ^& FormatNumber^(cdbl^(%c^)/1024/1024/1024, 2^)^& " GB" > %temp%\tmp.vbs & @if not "%c"=="" @echo( & @cscript //nologo %temp%\tmp.vbs & del %temp%\tmp.vbs) > E:\monitoring_scripts\log\Disk_status.txt

Output

C: free=79,11 GiB size=111,45 GiB
D: free=929,47 GiB size=931,51 GiB

Best Answer

Double the % sign denoting loop control variables: %a to %%a, %b to %%b and so on:

@ECHO OFF
SETLOCAL enableextensions
(for /f "tokens=1-3" %%a in ('
  WMIC LOGICALDISK GET FreeSpace^,Name^,Size ^|FINDSTR /I /V "Name"
  ') do (
    echo wsh.echo "%%b" ^& " free=" ^& FormatNumber^(cdbl^(%%a^)/1024/1024/1024, 2^)^& " GB"^& " size=" ^& FormatNumber^(cdbl^(%%c^)/1024/1024/1024, 2^)^& " GB" > "%temp%\tmp.vbs"
    if not "%%c"=="" (
      echo( 
      cscript //nologo "%temp%\tmp.vbs"
      del "%temp%\tmp.vbs"
    )
  )
) > E:\monitoring_scripts\log\Disk_status.txt

or, with less disk writes to the %temp% folder and with the only cscript call:

@ECHO OFF
SETLOCAL enableextensions
(for /f "tokens=1-3" %%a in ('
  WMIC LOGICALDISK GET FreeSpace^,Name^,Size ^|FINDSTR /I /V "Name"
  ') do (
    if not "%%c"=="" (
      echo wsh.echo vbNewLine ^& "%%b" ^& " free=" ^& FormatNumber^(cdbl^(%%a^)/1024/1024/1024, 2^)^& " GB"^& " size=" ^& FormatNumber^(cdbl^(%%c^)/1024/1024/1024, 2^)^& " GB"
    )
  )
) > "%temp%\tmp.vbs"
cscript //nologo "%temp%\tmp.vbs" > E:\monitoring_scripts\log\Disk_status.txt
del "%temp%\tmp.vbs"

Resources (further reading): An A-Z Index of the Windows CMD command line

Related Question