-1

These are my .bat scripts.

for /f "tokens=1-3 delims==" %%a in ('wmic computersystem get totalphysicalmemory /Value') do set /a "mem=%%b/1024/1024"
echo %mem% 
Squashman
  • 13,649
  • 5
  • 27
  • 36
  • 1
    Possible duplicate of [Get size of a directory in 'MB' using batch file](https://stackoverflow.com/questions/36301198/get-size-of-a-directory-in-mb-using-batch-file). Also related is [how can i get disk space with decimal point in gb tb and mb](https://stackoverflow.com/questions/37316364/how-can-i-get-disk-space-with-decimal-point-in-gb-tb-and-mb) and [Batch script doesn't run, although its code runs in CMD](https://stackoverflow.com/q/51090280) (ignore the misleading title here). – aschipfl Jul 04 '18 at 17:17

1 Answers1

2

The question uses /1024/1024 so I assume that we want the memory size in mebibytes (= 2^20 bytes). If we want decimal megabytes then of course all we neeed to do is to discard the last 6 digits.

    @echo off

    setlocal

    set "mem="
    for /f "tokens=2 delims==" %%a in (
      'wmic computersystem get totalphysicalmemory /value'
    ) do for /f "delims=" %%b in (
      "%%~a"
    ) do if not defined mem set "mem=%%~b"

::  At this point %mem% is the memory size in bytes. In order to convert to
::  mebibytes we need to divide by 2^20. However, set /a cannot work with
::  numbers greater than 2^31-1; we first convert to decimal megabytes and then
::  multiply by 0.95346.
::  (This will underestimate the mebibytes a little, by about 0.025%.)

    set "memMB=%mem:~0,-6%"
    set /a "mem=((memMB-memMB/21) + (memMB-memMB/22))/2"

    echo This computer has %mem% MiB RAM
  • tokens=2 because the result returned by wmic looks like

    TotalPhysicalMemory=25697566720
    ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^
    1st token           2nd token
    
  • First set and then set /a because for /f will include a carriage-return in the token, and trying to use it directly with set /a will generate an error.

  • set /a works in 32-bit two's complement arithmentic, so if %mem% is greater than 2147483647 we cannot simply compute %mem% / 1024 / 1024.

AlexP
  • 4,370
  • 15
  • 15
  • 1
    This works only for values < 2 GiB due to 32-bit limitation of CMD's integer arithmetics... – aschipfl Jul 04 '18 at 17:11
  • 1
    @aschipfl: Thank you for the timely reminder. I included a workaround. – AlexP Jul 04 '18 at 17:50
  • @AlexP Thanks alex! That helped! Im new to batchfile scripting. Would like to ask what does the '~' represent? – Jeremiah Kan Jul 06 '18 at 01:17
  • `for /?` and `set /?` will help you understand notations like `"%%~a` and `%mem:~0,6%`. – AlexP Jul 06 '18 at 08:53
  • Why not use powershell to do the math ? Eg For /F "Tokens=1" %%I in ('powershell -command "[Math]::Floor([decimal]((%TOTAL_PHYSICAL_MEMORY%/4)*3)/1024/1024)"') Do Set VBOX_PHYSICAL_MEMORY=%%I – mark d drake Jan 27 '20 at 18:18