批次檔中取得磁碟/分割區大小

批次檔中取得磁碟/分割區大小

如何獲得總尺寸批次檔中的磁碟或分割區(具有 1 個 NTFS 分割區的 USB 硬碟)?
我寧願不採用遞歸地遍歷文件的邏輯(具有 for /f 的邏輯),因為它是 1TB 驅動器,並且可能需要很長時間才能確定大小。

我願意使用一些小型第三方工具,它將返回批次檔的大小。

PS:我使用的是 Windows 7 x64 Ultimate

答案1

可能有一種更簡單的方法可以做到這一點,但這是我使用的

如果您想要的只是一個字節,您只需執行此命令,將 T 變更為外部磁碟機號碼(對於命令提示字元處的單行變更%%%和)set space=echo

for /f "tokens=3 delims= " %%a in ('dir /-c T: ^| find "bytes free"') do set space=%%a

如果您想採用並簡化它,請先為每種尺寸設定指導方針

set divide=1073741824&&set size=gigabytes
if %space% lss 1073741824 set divide=1048576&&set size=megabytes
if %space% lss 1048576 set divide=1024&&set size=kilobytes
if %space% lss 1024 set divide=1&&set size=bytes

然後編寫一個臨時 VBS 腳本,因為批次無法處理數學

echo wsh.echo cdbl(%space%)/%divide% > %temp%\tmp.vbs

運行它,捕獲結果並將其刪除

for /f %%a in ('cscript //nologo %temp%\tmp.vbs') do set space=%%a
del %temp%.\tmp.vbs

然後將結果修剪到小數點後兩位

for /f "tokens=1,2 delims=." %%a in ("%space%") do (
  set s1=%%a
  set s2=%%b
)
if not "%s2%"=="" (set space=%s1%.%s2:~0,2%) else (set space=%s1%)

回波結果

echo Drive has %space% %size% free.

[編輯]

為了全部的大小,可以使用diskpart listvolume("%%a"=="T"改為"%%a"=="driveletterhere"

for /f "tokens=3,6,7 delims= " %%a in ('echo list volume ^| diskpart') do if "%%a"=="T" set size=%%b && set size2=%%c

以及如何計算的獎金:

if [%size2%]==[TB] (
    set isBigEnough=1
) else if [%size2%]==[GB] (
    if %size% GTR 31 set isBigEnough=1
)
if not defined isBigEnough set isBigEnough=0

答案2

也許嘗試df.exe一下可以從http://unxutils.sourceforge.net/和其他地點。這是 UNIX 命令列工具的副本。

您還應該能夠直接從 Windows 管理介面 (WMI) 取得值,但恐怕我在該領域的技能不足以給出直接答案。

fsutil volume diskfree c:將為您提供 3 行輸出,您可以使用findon 來獲得您想要的結果。

輸出範例:

Total # of free bytes        : 466333454336
Total # of bytes             : 972999880704
Total # of avail free bytes  : 466333454336

fsutil volume diskfree c: | find "Total # of bytes"給你一條特定的線。

for /F "tokens=2 delims=:" %i in ('fsutil volume diskfree c: ^| find "Total # of bytes"') do @set USED=%i

給出前面帶有空格的數字。

進行比較:

@REM 32MB = 32*1024*1024 bytes
@set COMP=33554432

@REM Pull out the line containing the number of bytes USED
for /F "tokens=2 delims=:" %i in ('fsutil volume diskfree c: ^| find "Total # of bytes"') do @set USED=%i

@REM Drop the leading space character to just get the number so a numeric comparison is done
for /F "tokens=1 delims= " %i in ('echo %USED%') do @set USED=%i

@REM Tell me something useful
if %USED% lss %COMP% @echo "Used is less than 32MB"
if %USED% gtr %COMP% @echo "Used is greater than 32MB"

注意:fsutil 需要管理員權限,因此這可能無法在鎖定的電腦上執行。

相關內容