How can I convert this raw bytes output to GB?

前端 未结 5 1925
陌清茗
陌清茗 2020-12-21 07:08

I\'m using the below code to output the current free space on the C: Drive. How can I convert the output from bytes to GB using batch?

@echo off
for /f \"use         


        
5条回答
  •  既然无缘
    2020-12-21 07:46

    Could use the StrFormatByteSize64() API function to convert a long int to human readable size. This results in a more accurate value than truncating to meet the cmd environment's 32-bit limit. This API function supports values in the ranges from bytes and kilobytes to petabytes and exabytes.

    (This script is a hybrid Batch + PowerShell script. Save it with a .bat extension.)

    <# : batch portion
    @echo off & setlocal
    
    for /f "tokens=2 delims==" %%x in (
        'wmic logicaldisk where "DeviceID='C:'" get FreeSpace /value'
    ) do call :int2size FreeSpace %%x
    
    echo %FreeSpace% free on C:
    
    rem // end main runtime
    exit /b
    
    rem // batch int2size function
    :int2size  
    setlocal
    set "num=%~2"
    for /f "delims=" %%I in (
        'powershell -noprofile "iex (${%~f0} | out-string)"'
    ) do endlocal & set "%~1=%%I" & goto :EOF
    
    : end batch / begin PowerShell #>
    Add-Type @'
    using System.Runtime.InteropServices;
    namespace shlwapi {
        public static class dll {
            [DllImport("shlwapi.dll")]
            public static extern long StrFormatByteSize64(ulong fileSize,
                System.Text.StringBuilder buffer, int bufferSize);
        }
    }
    '@
    
    $sb = new-object Text.StringBuilder 16
    [void][shlwapi.dll]::StrFormatByteSize64($env:num, $sb, 16)
    $sb.ToString()
    

提交回复
热议问题