Generate MD5 Hash of Text Files in a Specific Directory: A Batch File Guide

Abstract: Automate MD5 hash generation for text files in a directory using native Windows certutil and batch scripting.

Created: 2026-08-06 by

Use the built-in certutil command in a Windows batch script to generate MD5 hashes for text files. By combining for /r with dir filtering, you can target specific directories and file extensions efficiently. This method requires no external tools and works natively on modern Windows versions.

Understanding the Native Hashing Tool

Windows includes a powerful utility called certutil that is capable of generating various cryptographic hashes, including MD5. While third-party tools like PowerShell or Python are common, relying on native commands ensures compatibility across different system configurations without requiring additional installations. The syntax for hashing a single file is straightforward: certutil -hashfile filename.txt MD5. However, executing this command manually for every file in a directory is inefficient. Therefore, we must automate the process using batch scripting logic. The output of certutil typically includes two lines of hash data along with some header information. For clean processing, we usually only need the hexadecimal string itself. Understanding how to parse this output is crucial for integrating it into larger scripts or logs. We will explore how to isolate just the hash value in the subsequent steps.

Constructing the Directory Loop

To process multiple files, we need a loop that traverses the directory structure. The for /r command is ideal for this purpose as it recursively iterates through all subdirectories. You must specify the starting path and the file pattern. For example, to target all text files in C:\Data\Logs, the base command looks like this: for /r "C:\Data\Logs" %%F in (*.txt) do .... Note that we use double percent signs (%%F) inside a batch file, whereas a single percent (%F) is used when typing directly into the command prompt. It is important to handle spaces in file paths correctly. If your directory contains spaces, such as C:\My Documents\Files, you must enclose the path in quotes. Failure to do so often results in errors where the command interpreter misinterprets the space as a delimiter between arguments. For more details on handling these path issues, see Batch File Not Working with Space in File Name. Additionally, if you plan to chain other operations after hashing, be aware of return codes. See Windows Command Prompt: Command Chaining and Non-Zero Return Values to ensure your script continues smoothly even if individual commands behave unexpectedly.

The Complete Batch Script

Below is a robust script that generates MD5 hashes for all text files in a specified directory and outputs them to a log file. This script handles recursive searching, filters for .txt files, and cleans up the certutil output to provide just the hash and filename.
@echo off
setlocal enabledelayedexpansion

:: Define the target directory
set "TargetDir=C:\Path\To\Your\TextFiles"

:: Define the output log file
set "LogFile=MD5_Hashes.log"

:: Clear the log file if it exists
if exist "%LogFile%" del "%LogFile%"

echo Generating MD5 hashes for text files in %TargetDir%...

:: Loop through all .txt files recursively
for /r "%TargetDir%" %%F in (*.txt) do (
    :: Check if the file exists and is not empty (optional safety check)
    if exist "%%F" (
        :: Get the hash using certutil
        for /f "tokens=2 delims=:," %%H in ('certutil -hashfile "%%F" MD5 ^| findstr /i "MD5"') do (
            :: Trim whitespace from the hash
            set "Hash=%%H"
            set "Hash=!Hash: =!"
            
            :: Append filename and hash to the log
            echo %%~nxF !Hash! >> "%LogFile%"
        )
    )
)

echo Done. Results saved to %LogFile%
pause
This script uses nested loops. The outer loop finds the files, and the inner loop processes the output of certutil. The findstr command helps locate the line containing the actual hash value, and tokens=2 delims=:, splits that line to extract the hexadecimal string. The set "Hash=!Hash: =!" line removes any leading or trailing spaces that might remain, ensuring the output is clean. If you need to execute multiple complex commands within this loop, consider reviewing best practices for multi-command execution. Refer to Making Bat Files Execute Multiple Commands at Once for advanced techniques on managing command flow and error levels within your batch scripts.

Scheduling and Automation

Once you have verified that the script works correctly, you may want to run it automatically. Windows Task Scheduler is the most reliable way to achieve this. You can configure the scheduler to run the batch file daily, weekly, or upon specific events. This is particularly useful for integrity checking large sets of data. For a step-by-step guide on setting up these automated runs, consult Scheduling a Task to Start a Batch File with Windows Task Scheduler.

Frequently Asked Questions

Can I use SHA256 instead of MD5?

Yes, simply replace MD5 with SHA256 in the certutil command. The rest of the script remains identical because certutil supports multiple algorithm identifiers natively.

Why does my script fail on files with spaces?

This usually happens because the file path is not enclosed in quotes within the for loop or the certutil call. Always wrap "%%F" in quotes to ensure the command processor treats the entire path as a single argument.

How do I exclude hidden files from the hash?

You can add the /a switch to the dir command if you were using it, but with for /r, you typically need to check attributes. Add an if not exist "%%F\." check or filter by attributes using %%~aF to skip hidden or system files before processing.

Is MD5 secure for verifying file integrity?

MD5 is fast but vulnerable to collision attacks, meaning two different files could theoretically produce the same hash. For security-critical applications, use SHA256 or higher. For simple checksums to detect accidental corruption, MD5 is still widely accepted.

Can I get the full path in the output log?

Yes, replace %%~nxF in the echo statement with %%~fF. This variable expansion prints the fully qualified path of the file, which is helpful if you are scanning multiple subdirectories.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More