Batch files compare numbers

2019-09-08 07:25发布

I have to write a script that check if there is enough space in the drive. I wrote the following:

@echo off
set gbsize = 1,073,741,824
Set gbsize=%gbsize:,=%
for /f "tokens=3" %%a in ('dir c:\') do (
    set /a bytesfree=%%a
)
set bytesfree=%bytesfree:,=%
endlocal && set bytesfree=%bytesfree%

If %gbsize% gtr %bytesfree% echo hi

but when the script thrown error: Invalid number. Numeric constants are either decimal (17), hexadecimal (0x11), or octal (021).

what did I miss? can anyone help? thanks!

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-08 07:42

Your immediate problem is attempting to use SET /A when there are commas in your value.

You also need to remove the spaces before and after = when you define gbsize.

I don't understand why you have endlocal without a setlocal

I believe this is what you were looking for. It will echo "hi" if there is less then 1GB free space.

@echo off
setlocal
set gbsize=1,073,741,824
Set gbsize=%gbsize:,=%
for /f "tokens=3" %%a in ('dir c:\') do set bytesfree=%%a
set bytesfree=%bytesfree:,=%
If %gbsize% gtr %bytesfree% echo hi

Another, more direct, (and possibly more accurate?) way to get the free space

for /f "tokens=2" %%S in ('wmic volume get DriveLetter^, FreeSpace^|find "C:"') do set bytesfree=%%S
查看更多
登录 后发表回答