从可用空间获取所需空间并存储在变量中

时间:2017-02-11 12:09:16

标签: batch-file cmd

好的,我有这段代码:

echo [%time%] Beginning install
echo [%time%] Checking hard drive C:\
for /f "usebackq tokens=* delims=" %%# in (`"wmic logicaldisk  where name='C:' get  FreeSpace /format:value"`) do (
    for /f "tokens=* delims=" %%a in ("%%#") do @set "%%a"
)
echo [%time%] Available space: %freespace% Bytes
echo [%time%] Required space: 34 Megabytes
@set requiredspace=34
@set /a "available_required=%freespace%-%requiredspace%"
echo [%time%] %available_required%
pause

它找到了硬盘驱动器上的可用存储空间并带走了查看是否有足够的存储空间来完成安装所需的内容,不幸的是,Windows CMD不喜欢高于32位的数字,所以我需要将其削减对于兆字节,数学不能对存储的变量进行,因此必须直接从命令中找到它。 例如,(显然不工作)

"wmic logicaldisk  where name='C:' get  FreeSpace /format:value /division:megabytes"

由于

3 个答案:

答案 0 :(得分:1)

您可以直接将自由空间计算的powershell直接用于​​MegaBytes,而不是使用WMIC:

@Echo Off

For /F "Delims=" %%A In ('Powershell "gWMI Win32_LogicalDisk"^
 "-F ""DeviceID='C:'""""|%%{[Math]::Round($_.FreeSpace/1MB,0)}"'
) Do Set "FDS=%%A"
Echo=Freespace on C: is %FDS%MB

Timeout -1

如果您正在寻找两位小数的GB,那么快速编辑上述内容也可以实现:

@Echo Off

For /F "Delims=" %%A In ('Powershell "gWMI Win32_LogicalDisk"^
 "-F ""DeviceID='C:'""""|%%{[Math]::Round($_.FreeSpace/1GB,2)}"'
) Do Set "FDS=%%A"
Echo=Freespace on C: is %FDS%GB

Timeout -1

答案 1 :(得分:0)

快速和肮脏的:

set "freespace=%freespace:~0,-6%"
echo [%time%] Available space: %freespace% MBytes

将自由空间除以1,000,000而不是1024 ^ 2

答案 2 :(得分:0)

您可以填充值并将它们作为字符串进行比较

set "rSpace=00000000000035651584"
set "fSpace=00000000000000000000%freeSpace%"
if "%rSpace:~-20%" gtr "%fSpace:~-20%" (
    echo [%time%] Not enough space available
) else (
    echo [%time%] Enough Space available
)