Search code examples
windowsbatch-filespacewmic

Using wmic to get drives space information


I'm trying to get info of the physical drives in a computer with wmic to get something like this:

Drive C:
500 GB Total
100 GB Free
20% Free

Drive D:
500 GB Total
100 GB Free
20% Free

My code so far is:

for /f "usebackq tokens=*" %%a in (`wmic logicaldisk where "drivetype=3" get caption`) do (
echo "Drive=%%a"
for /f "usebackq delims== tokens=2" %%x in (`wmic logicaldisk where DeviceID='%%a'"       
get FreeSpace /format:value`) do set FreeSpace=%%x
for /f "usebackq delims== tokens=2" %%x in (`wmic logicaldisk where "DeviceID='%%a'" get Size /format:value`) do set Size=%%x
echo FreeMB=%FreeSpace%
echo SizeMB=%Size%
set /a Percentage=100 * %FreeSpace% / %Size%
echo %%a is %Percentage% %% free
)

And my output is:

"Drive=Caption
No Instance(s) Available.
No Instance(s) Available.
FreeMB=9193357312
SizeMB=80024170496
Invalid number.  Numbers are limited to 32-bits of precision.
 is  % free
"Drive=C:
No Instance(s) Available.
No Instance(s) Available.
FreeMB=9193357312
SizeMB=80024170496
Invalid number.  Numbers are limited to 32-bits of precision.
is  % free
"Drive=E:
No Instance(s) Available.
No Instance(s) Available.
FreeMB=9193357312
SizeMB=80024170496
Invalid number.  Numbers are limited to 32-bits of precision.
 is  % free
"Drive=
No Instance(s) Available.
No Instance(s) Available.
FreeMB=9193357312
SizeMB=80024170496
Invalid number.  Numbers are limited to 32-bits of precision.
 is  % free

I'm getting to many lines that don't even have a drive and I can't format the value so I can calculate the percentage, or show the values in a normal format


Solution

  • This may work for you: the code is to be added at the bottom of your batch file, and use

    call :hdd-info

    in your code to display the data.

    goto :eof
    :code by aGerman - display drive stats and bar graph (REMmed out)
    :hdd-info    
    @echo off &setlocal
    set "GB=1073741824"
    for /f "skip=1 delims=" %%i in ('wmic logicaldisk get DeviceID^,FreeSpace^,Size') do (
      for /f "tokens=1-3" %%j in ("%%i") do call :output %%j %%k %%l
    )
    goto :eof
    :output
    if "%3"=="" (
      rem echo Unable to discover the drive properties.
      goto :eof
    )
    for /f "tokens=1-4" %%i in (
      'mshta vbscript:Execute("CreateObject(""Scripting.FileSystemObject"").GetStandardStream(1).Write(FormatNumber(%3/%GB%, 2) & "" "" & FormatNumber((%3-%2)/%GB%, 2) & "" "" & FormatNumber(%2/%GB%, 2) & "" "" & Round((%3-%2)*50/%3)):Close"^)'
    ) do (
      set "size=      %%i"
      set "used=      %%j"
      set "free=      %%k"
      set /a "nUsed=%%l, nFree=50-%%l"
    )
    echo(
    echo       %1
    echo Size: %size:~-10% GB
    echo Used: %used:~-10% GB
    echo Free: %free:~-10% GB
    :: echo(
    :: for /l %%i in (1 1 %nUsed%) do <nul set /p "=▒"
    :: for /l %%i in (1 1 %nFree%) do <nul set /p "=█"
    :: echo(&echo(&echo(
    goto :eof