使用Windows批处理文件将字节转换为MB

时间:2014-04-17 13:06:42

标签: windows batch-file

我有这个简短的剧本

@echo off
for %%i in (*.msu) do (
   echo %%i - %%~zi
)

它显示:

Windows8.1-KB2919355-x64.msu - 724339463
Windows8.1-KB2932046-x64.msu - 50327684
Windows8.1-KB2934018-x64.msu - 132577686
Windows8.1-KB2937592-x64.msu - 309819
Windows8.1-KB2938439-x64.msu - 20533883

如何以MB为单位显示字节
我知道我需要制作这个转换字节/ 1024/1024但是如何在批处理脚本中执行此操作?

3 个答案:

答案 0 :(得分:2)

Inspired from here它适用于您在下面的短代码中克服批量数学的2GB限制:

@if (@CodeSection == @Batch) @then

@echo off
setlocal enabledelayedexpansion
set JScall=Cscript //nologo //E:JScript "%~F0"
for /f "tokens=1,3 delims= " %%i in (input.txt) do (
      for /f %%a in ('%JScall% "%%j/1024/1024"') do set a=%%a
      for /f "delims=." %%z in ("!a!") do set a=%%z
      echo %%i     !a!>>newout.txt
   )
)
goto :EOF

@end
WScript.Echo(eval(WScript.Arguments.Unnamed.Item(0)));

其中 input.txt 是:

Windows8.1-KB2919355-x64.msu - 724339463
Windows8.1-KB2932046-x64.msu - 50327684
Windows8.1-KB2934018-x64.msu - 132577686
Windows8.1-KB2937592-x64.msu - 309819
Windows8.1-KB2938439-x64.msu - 20533883
Windows8.1-KB2938439-x64.msu - 3724339463

您的 newout.txt 会显示为:

Windows8.1-KB2919355-x64.msu     690
Windows8.1-KB2932046-x64.msu     47
Windows8.1-KB2934018-x64.msu     126
Windows8.1-KB2937592-x64.msu     0
Windows8.1-KB2938439-x64.msu     19
Windows8.1-KB2938439-x64.msu     3551

答案 1 :(得分:1)

您可以使用set /a进行算术运算:

set /a size=%%~zi / 1024 / 1024
echo %%i - !size!

您需要使用

启用延迟扩展
setlocal enabledelayedexpansion
不过,首先是

答案 2 :(得分:1)

如果您的值高达32位整数,则适合您:

@echo off
call :Parse > output.txt
exit /b 0

:Parse
for /f "tokens=1,3 delims= " %%A in (input.txt) do call :ToMB "%%~B" "%%~A"|| echo(%%A %%B 
exit /b 0

:IsNumber <String>
for /f "delims=0123456789" %%A in ("%~1") do exit /b 1
exit /b 0

:ToMB <String> <Name>
setlocal
call :IsNumber "%~1" || exit /b 1
set "Number=%~1"
set /a "Number/=1024"
set /a "Decimal=Number"
set /a "Number/=1024"
set /a "Decimal-=(Number * 1024)"
set /a "Decimal=(Decimal * 1000) / 1024"
set "Decimal=000%Decimal%"
set "Number=   %Number%"
set "Name=%~2            "
echo %Name:~0,30%%Number:~-3%.%Decimal:~-3%
endlocal
exit /b 0

input.txt 是:

Windows8.1-KB2919355-x64.msu - 724339463
Windows8.1-KB2932046-x64.msu - 50327684
Windows8.1-KB2934018-x64.msu - 132577686
Windows8.1-KB2937592-x64.msu - 309819
Windows8.1-KB2938439-x64.msu - 20533883

您将 output.txt 改为:

Windows8.1-KB2919355-x64.msu  690.783
Windows8.1-KB2932046-x64.msu   47.996
Windows8.1-KB2934018-x64.msu  126.435
Windows8.1-KB2937592-x64.msu    0.294
Windows8.1-KB2938439-x64.msu   19.582

...因此所有值都从字节转换为MB。