Windows 10

How to Check the Size of a File in a Windows Batch Script

In this tutorial, you’ll learn how to use a batch file to check the size of a file in Windows. A batch file automates repetitive tasks by executing a series of DOS (Disk Operating System) commands.
 

✅ Use Case: Check If a File Exceeds a Maximum Size Limit

You can use a batch script to determine the size of a file and compare it to a predefined maximum size. This is helpful for tasks like:

  • Validating log files before backup
  • Monitoring file growth
  • Automated cleanup based on file size
 

📄 Batch File Example:
@echo off
set "file=file1.txt"
set MAXBYTESIZE=500
FOR %%A IN (%file%) DO set size=%%~zA

if %size% GTR %MAXBYTESIZE% (
    echo %file% is too large
) else (
    echo %file% is %size% bytes long
)

📤 Output:

file1.txt is too large

or:

file1.txt is 340 bytes long

 

🧠 Explanation of the Commands:
Command Description
set "file=file1.txt" Sets the filename to check.
set MAXBYTESIZE=500 Defines the maximum allowed file size in bytes.
%%~zA Returns the size (in bytes) of the file %%A.
if %size% GTR %MAXBYTESIZE% Compares the actual size with the limit.
echo Prints the result to the console.

 

🔄 Modify It for Dynamic Checks

You can adapt this script to check multiple files, or log the results to a .txt file:

@echo off
set MAXBYTESIZE=500
for %%F in (*.txt) do (
    set size=0
    for %%A in ("%%F") do set size=%%~zA
    if !size! GTR %MAXBYTESIZE% (
        echo %%F is too large
    ) else (
        echo %%F is !size! bytes long
    )
)

👉 Note: Add setlocal enabledelayedexpansion at the top to support !size! in loops.
 

🧰 Tools & Use Cases
  • 🔍 Monitor backup file sizes.
  • 🚫 Block upload if file exceeds size.
  • 📈 Alert admin when log files grow too large.

One thought on “How to Check the Size of a File in a Windows Batch Script

  • John Crosby

    How are you handling the error due to a zero-byte file using this technique?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *