如何在GB或TB的存储介质上获得2个小数位的可用空间?

时间:2016-05-19 10:56:35

标签: batch-file

如何在GB中的存储介质上获得可用空间,或者在TB中以超过1024 GB的小数位数获得2个小数位?

以下是我的代码:

:: Example batch file to show free disk space on C:

@echo off
cls
echo.
echo Free Space on C:
echo ========================================

for /f "tokens=1-3" %%n in ('"WMIC LOGICALDISK GET Name,Size,FreeSpace | find /i "C:""') do set free=%%n& set total=%%p
echo.
rem echo %free% bytes free

set free=%free:~0,-3%
set /a free=%free%/1049
echo.
rem echo %free% MB free (approx and underestimated)

set /a free=%free%/1024
echo.
echo %free% GB free

pause > NUL

1 个答案:

答案 0 :(得分:1)

由于CMD变量只能作为整数使用数字,因此您必须采取一些技巧来手动放置小数点。这样的事情应该有效:

setlocal enabledelayedexpansion

for /f "tokens=1-3" %%n in ('"WMIC LOGICALDISK GET Name,Size,FreeSpace | find /i "C:""') do set "freeB=%%n" & set "totalB=%%p"

set /a freeMB=%freeB:~0,-3%/1049
set /a freeGB=%freeB:~0,-3%/1049/1024

if %freeGB% geq 1000 (
    set /a freeTB=%freeGB%*1000/1024
    set freeTB=!freeTB:~0,-3!.!freeTB:~-3,-1!
)

if %freeMB% geq 1000 (
    set /a freeGB=%freeMB%*1000/1024
    set freeGB=!freeGB:~0,-3!.!freeGB:~-3,-1!
)

if defined freeTB echo %freeTB% TB Free 
if defined freeGB echo %freeGB% GB Free 
pause

所以我一直在玩这个只是为了好玩。一句话:批处理文件对于数学来说真的非常糟糕。 CMD无法处理小数,并且无法处理超过2147483647的任何数字,这使得使用Bytes和TeraBytes的数字非常麻烦。那就是说,这就是我想出的。它仍然有局限性:它不会显示KB和MB范围内的大小,但它可以非常准确地处理GB和TB。我也开始在功能中使用输入和输出,所以也就是这样。

@echo off   

for /f "tokens=1-3" %%n in ('"WMIC LOGICALDISK GET Name,Size,FreeSpace | find /i "C:""') do (
    set "freeB=%%n" 
    set "totalB=%%p"
)

rem use these to manually set your values for testing...
rem set freeB=581881856
rem set totalB=3000581881856

call :ConvertBytes %totalB% totalMB totalGB totalTB
call :ConvertBytes %freeB% freeMB freeGB freeTB

call :GetRightSizeAndInsertDecimal %totalGB% %totalMB% totalGBwDec
call :GetRightSizeAndInsertDecimal %totalTB% %totalGB% totalTBwDec
call :GetRightSizeAndInsertDecimal %freeGB% %freeMB% freeGBwDec
call :GetRightSizeAndInsertDecimal %freeTB% %freeGB% freeTBwDec

echo total space:
if defined totalTBwDec echo %totalB% Bytes (%totalTBwDec% TB)
if defined totalGBwDec echo %totalB% Bytes (%totalGBwDec% GB)
echo.
echo free space:
if defined freeTBwDec echo %freeB% Bytes (%freeTBwDec% TB)
if defined freeGBwDec echo %freeB% Bytes (%freeGBwDec% GB)
pause
goto :eof

:ConvertBytes   {bytes} {MB} {GB} {TB}
set bytes=%1
set /a %3=%Bytes:~0,-6%/1074
set /a %2=%Bytes:~0,-6%*1024/1074
set /a %4=%3/1024
exit /b

:GetRightSizeAndInsertDecimal   {check size} {stepdown size} {checksize w decimal}
if %1 lss 1000 if %1 gtr 0 (
    call :InsertDecimal %2 %3
)
exit /b

:InsertDecimal   {number} {number with decimal}
set /a newNum=%1*1000/1024
set "%2=%newNum:~0,-3%.%newNum:~-3,-1%" 
exit /b