get File Size batch script.

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Rajnishjc_27
Posts: 21
Joined: 16 Aug 2019 23:35

get File Size batch script.

#1 Post by Rajnishjc_27 » 19 Sep 2019 04:26

HI

Which command to get or read size of the file from particular folder.
like its kb or mb.

Hackoo
Posts: 75
Joined: 15 Apr 2014 17:59

Re: get File Size batch script.

#2 Post by Hackoo » 21 Sep 2019 01:29

Hi :wink:

Code: Select all

@echo off
Title Get size file from a batch file
SETLOCAL enabledelayedexpansion
Set "MyBatchFile=%0"
Set "MyFile=C:\temp\test.txt"
echo(
echo This batch file !MyBatchFile! has a size of %~z0 bytes
echo(
for %%A in ("%MyFile%") do (
	set "Size=%%~zA"
	echo The file "!MyFile!" has a size of !size! bytes
)
pause

Hackoo
Posts: 75
Joined: 15 Apr 2014 17:59

Re: get File Size batch script.

#3 Post by Hackoo » 22 Sep 2019 07:42

Hi :wink:
Here is another code using a small vbscript to convert size to KB,MB and GB

Code: Select all

@echo off
Title Get size of file or folder from a batch file by Hackoo 2019
SetLocal enabledelayedexpansion
Set "MyBatchFile=%0"
Set "MyFolder=%Temp%"
Set "LogFile=%~dp0SizeLog.txt"
If Exist "%LogFile%" Del "%LogFile%"
echo(
echo This batch file !MyBatchFile! has a size of %~z0 bytes
Call :GetSize %~z0
(
	echo This batch file !MyBatchFile! has a size of %~z0 bytes
	Call :GetSize %~z0
)>"!LogFile!"

for /f "delims=" %%A in ('Dir /s /b "%MyFolder%"') do (
	set "Size=%%~zA"
	set "PathName=%%~dpnxA"
	Call :FolderOrFile "!PathName!"
	echo has a size of !size! bytes
	Call :GetSize !size!
	(
		Call :FolderOrFile "!PathName!"
		echo has a size of !size! bytes
		Call :GetSize !size!
	)>>"!LogFile!"
)
If Exist "!LogFile!" Start "" "!LogFile!" & Exit
Rem ----------------------------------------------------------------------------
:GetSize <object>
(
	echo wsh.echo FormatNumber^(cdbl^("%~1"^)/1024, 2^)^& " KB"
	echo wsh.echo FormatNumber^(cdbl^("%~1"^)/1024/1024, 5^)^& " MB"
	echo wsh.echo FormatNumber^(cdbl^("%~1"^)/1024/1024/1024, 6^)^& " GB"
	echo wsh.echo String("100","-"^)
)>"%temp%\tmp.vbs"
cscript //nologo "%temp%\tmp.vbs"
del "%temp%\tmp.vbs"
Exit /b 
Rem ----------------------------------------------------------------------------
:FolderOrFile <Object>
REM How to test if a path is a file or directory in Windows batch file?
REM https://stackoverflow.com/questions/8666225/how-to-test-if-a-path-is-a-file-or-directory-in-windows-batch-file?answertab=active#tab-top
for /f "tokens=1,2 delims=d" %%A in ("-%~a1") do if "%%B" neq "" (
  echo The folder %1 
) else if "%%A" neq "-" (
  echo The file %1
) else (
  echo %1 does not exist
)
Exit /b 
Rem ----------------------------------------------------------------------------

Post Reply