Windows Command Line Batch Variable Substring with WMIC Output not Truncating Properly
Using Windows Batch all I want to do is get the specified drive size in MB (by drive letter) and corresponding free space available for that drive stored in a variable as an integer to do some basic math.
I use this script:
for /f "usebackq delims== tokens=2" %%x in (`wmic logicaldisk where "DeviceID='Z:'" get Size /format:value`) do
set SizeDisk=%%x
for /f "usebackq delims== tokens=2" %%x in (`wmic logicaldisk where "DeviceID='Z:'" get FreeSpace /format:value`) do
set FreeS=%%x
This gives me the values I want. However, when I go to truncate the last six digits to give me MB (it's close enough for my needs):
SET /A SizeDiskMB=%SizeDisk:~0,-6%
SET /A FreeSMB=%FreeS:~0,-6%
It only truncates the last five digits not six. If I use ~0,-7
then it give me proper values, but I'd like to understand why it does this. I also need these as integer values so I can do some basic math which is the reason for the /A
.
Thanks for any assistance.
EDIT:
OK, I realize I don't need the /A until I actually do the math. I thought it would set the variable as an integer, doesn't seem to be the case. So ignore that for now.
I ran the following code:
@ECHO OFF
cls
for /f "usebackq tokens=2 delims==" %%x in (`wmic logicaldisk where "DeviceID='Z:'" get Size /format:value`) do set SizeDisk=%%x
Echo Size Disk: %SizeDisk% bytes
Echo Size Disk 0,-1: %SizeDisk:~0,-1%
Echo Size Disk 0,-2: %SizeDisk:~0,-2%
Echo Size Disk 0,-3: %SizeDisk:~0,-3% KB
Echo Size Disk 0,-4: %SizeDisk:~0,-4%
Echo Size Disk 0,-5: %SizeDisk:~0,-5%
Echo Size Disk 0,-6: %SizeDisk:~0,-6% MB
Echo Size Disk 0,-7: %SizeDisk:~0,-7%
Pause
And received the following results:
Size Disk: 1887436795904 bytes <-- Same
Size Disk 0,-1: 1887436795904 <-- Same
Size Disk 0,-2: 188743679590
Size Disk 0,-3: 18874367959 KB
Size Disk 0,-4: 1887436795
Size Disk 0,-5: 188743679
Size Disk 0,-6: 18874367 MB
Size Disk 0,-7: 1887436
Press any key to continue . . .
"Size Disk"
and "Size Disk 0,-1"
are the same. It should not be.
Solution 1:
Edited: The wmic command must be returning extra spaces or linebreaks, to remove them use a double for:
@echo off
for /f "usebackq delims== tokens=2" %%x in (`wmic logicaldisk where "DeviceID='Z:'" get Size /format:value`) do for /f "Delims=" %%y in ("%%~x") do set SizeDisk=%%~y
for /f "usebackq delims== tokens=2" %%x in (`wmic logicaldisk where "DeviceID='Z:'" get FreeSpace /format:value`) do for /f "Delims=" %%y in ("%%~x") do set FreeS=%%~y
echo Disk Size: "%SizeDisk%" Bytes
echo Free Space "%FreeS%" Bytes
echo.
echo Disk Size: "%SizeDisk:~0,-6%" Mega Bytes
echo Free Space "%FreeS:~0,-6%" Mega Bytes
echo.
pause