How to Move Video Files to Separate Folders by Batch Script

Abstract: Batch script organizes video files into folders of forty by calculating group indices and using delayed expansion for accurate variable handling.

Created: 2026-09-04 by
A batch script can efficiently organize thousands of video files into separate folders by grouping them in sets of forty. By iterating through a directory, the script calculates the target folder name based on the current file count and moves each file accordingly. This approach ensures that each drama series or collection is split into manageable chunks without manual intervention.

Understanding the Grouping Logic

The core challenge involves tracking how many files have been processed to determine when to create a new folder. You need a counter that increments with every file moved. When this counter reaches the limit (40), you must increment a "group" variable and reset the counter for the next batch. This logic prevents all files from ending up in a single folder or creating an infinite loop of empty directories. The script relies on standard Windows command-line variables to maintain state across iterations within the same execution context.

The Batch Script Solution

Below is a complete, robust batch script that implements this logic. It assumes your video files are in a specific source directory and defines a destination root where the grouped folders will be created.
@echo off
setlocal enabledelayedexpansion

:: Configuration
set "SourceDir=C:\Videos\Raw"
set "DestRoot=C:\Videos\Organized"
set "GroupSize=40"

:: Initialize counters
set /a FileCount=0
set /a GroupNum=1

:: Ensure destination root exists
if not exist "%DestRoot%" mkdir "%DestRoot%"

:: Loop through all video files
for %%F in ("%SourceDir%\*.mp4" "%SourceDir%\*.mkv" "%SourceDir%\*.avi") do (
    set /a FileCount+=1
    
    :: Calculate which group folder this file belongs to
    set /a GroupIndex=(FileCount - 1) / GroupSize + 1
    
    set "GroupFolder=%DestRoot%\Drama_Group_!GroupIndex!"
    
    :: Create folder if it does not exist
    if not exist "!GroupFolder!" mkdir "!GroupFolder!"
    
    :: Move the file
    move "%%F" "!GroupFolder\"
    
    echo Moved "%%~nxF" to "!GroupFolder!"
)

echo Done. Total files processed: %FileCount%
pause
This script uses enabledelayedexpansion to correctly handle variable updates inside the loop. Without this setting, the variables would resolve only once at the start of the loop, leading to incorrect folder assignments. The calculation (FileCount - 1) / GroupSize + 1 ensures that files 1-40 go to Group 1, 41-80 to Group 2, and so on.

Adjusting File Types

The for loop explicitly lists common video extensions like .mp4, .mkv, and .avi. If you have other formats such as .wmv or .mov, simply add them to the list within the parentheses. Be careful not to include generic patterns like *.* unless you want to process every single file in the directory, including thumbnails or metadata files.

Common Pitfalls and Fixes

Many users encounter issues because they forget to enable delayed expansion. If you see errors about variables being undefined, ensure setlocal enabledelayedexpansion is at the top. Another common mistake is using %Variable% instead of !Variable! inside the loop body. Standard percent signs expand immediately before the loop starts, while exclamation marks expand during execution, reflecting the current iteration's value. If you find that files are not moving, check your permissions. Running the script as an administrator may be necessary if the source directory is protected. Additionally, verify that the path lengths do not exceed Windows' maximum limits, though modern versions of Windows 10 and 11 handle long paths better than previous versions. For more complex scheduling needs, you might consider integrating this script into Task Scheduler, as discussed in our guide on Powershell Script Not Running in Task Scheduler.

Verifying the Output

After running the script, navigate to your destination root folder. You should see subdirectories named Drama_Group_1, Drama_Group_2, etc. Each folder should contain exactly 40 files, except possibly the last one, which will contain the remainder of the total file count. Check a few folders to ensure the files were moved correctly and that no duplicates remain in the source directory. For troubleshooting variable persistence issues if you decide to refactor this into multiple scripts, refer to Persisting Windows Variables in CMD Files. This knowledge helps if you need to save the last processed group number for future incremental runs.

Frequently Asked Questions

What happens if I have fewer than 40 files?

The script will create a single group folder containing all available files. The math ensures that even one file triggers the creation of Group 1, so you won't end up with empty folders unless you have zero files to process.

Can I change the folder naming convention?

Yes, simply modify the line defining GroupFolder. You can use dates, episode ranges, or custom prefixes instead of Drama_Group_. Just ensure the string remains consistent and free of invalid filename characters.

Does this script work on network drives?

It works on network drives provided you have read/write permissions and the connection is stable. However, large batches over slow networks may time out. Consider processing smaller subsets if you experience connectivity drops.

How do I handle files with spaces in their names?

The script already accounts for spaces by quoting the paths around variables like "%%F" and "!GroupFolder!". This ensures that filenames with spaces are treated as single entities rather than broken arguments.

Can I run this script repeatedly without duplicating files?

No, because move removes the file from the source. If you re-run it on the same source directory, it will find no files left. To avoid accidental data loss, always back up your source directory before running bulk move operations.

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