Encode Multiple Video Files in One Main Folder with Multiple Subfolders (h.265, new name)?

Abstract: Batch encode nested video files to H.265 with new names using FFmpeg and PowerShell or Bash loops.

Created: 2026-10-25 by
You can batch encode all video files in a main folder and its subdirectories to H.265 with new names using FFmpeg combined with a simple shell script or PowerShell loop. This approach recursively finds every supported media file, applies the libx265 encoder, preserves audio streams, and outputs the result into a designated destination folder while renaming files based on your preferred naming convention.

Understanding the Directory Structure

Before writing any commands, it is crucial to define how your source and destination folders are organized. The goal is to process files from a root directory that contains multiple subfolders, each potentially holding various video formats like MP4, MKV, or AVI. You need a strategy that traverses this hierarchy without manually opening each folder. FFmpeg itself does not have a built-in recursive file finder; it processes one input at a time. Therefore, you must use an external tool to iterate through the directory tree. On Windows, PowerShell is ideal for this task due to its robust string manipulation capabilities. On macOS and Linux, Bash with the find command provides equivalent functionality. The key challenge is ensuring that the output path mirrors the input structure or places all encoded files into a single new location, depending on your storage preferences.

Setting Up the Encoding Parameters

To achieve high-quality compression with the H.265 codec, you must configure specific FFmpeg flags. The primary encoder is libx265. However, simply calling this encoder is not enough for optimal results. You should set the -crf (Constant Rate Factor) value to control quality versus file size. A CRF of 28 is generally considered visually lossless for most content, while lower values like 20-23 offer higher quality at the cost of larger files. Additionally, you must handle audio streams correctly. If you do not specify audio handling, FFmpeg might drop them or re-encode them unnecessarily. Use -c:a copy to stream-copy the audio, which saves significant processing time and avoids generation loss. For the video stream, use -c:v libx265. It is also advisable to include -pix_fmt yuv420p10le if you want 10-bit color depth, which improves gradient handling, though standard yuv420p is sufficient for most playback devices. For more details on comparing encoding efficiencies, you might find FFmpeg vs LAME: Equivalent MP3 Encoding with Low CBR useful, as the principles of bitrate management apply similarly across video and audio codecs.

Implementing the Loop on Windows

PowerShell offers a straightforward way to iterate through directories. First, define your source root directory and your destination directory. Then, use the Get-ChildItem cmdlet with the -Recurse flag to locate all video files. You will need to filter these by extension, such as *.mp4, *.mkv, etc. Inside the loop, construct the output filename. To rename the files, you can strip the original extension and append a suffix like _encoded.mp4, or replace the entire name with a timestamp or sequential number. The command structure within the loop would look like this:
$sourcePath = "C:\Videos\Source"
$destPath = "C:\Videos\Encoded"

Get-ChildItem -Path $sourcePath -Include *.mp4,*.mkv,*.avi -Recurse | ForEach-Object {
    $inputFile = $_.FullName
    $outputFile = Join-Path $destPath ($_.BaseName + "_h265.mp4")
    
    ffmpeg -i $inputFile -c:v libx265 -crf 28 -c:a copy -y $outputFile
}
This script processes each file sequentially. The -y flag overwrites existing output files without prompting, which is essential for automation. Note that if your subfolders contain many files, this process may take considerable time depending on your CPU power.

Implementing the Loop on macOS and Linux

On Unix-like systems, the find command is the standard tool for locating files. You can combine it with exec or a while read loop to pass filenames to FFmpeg. Because filenames can contain spaces, it is critical to handle them safely. Using find ... -print0 and reading with -d '' ensures that spaces and special characters do not break the command.
#!/bin/bash
SOURCE_DIR="./source_videos"
DEST_DIR="./encoded_videos"

mkdir -p "$DEST_DIR"

find "$SOURCE_DIR" -type f \( -name "*.mp4" -o -name "*.mkv" \) -print0 | while IFS= read -r -d '' file; do
    filename=$(basename "$file")
    basename_no_ext="${filename%.*}"
    output_file="$DEST_DIR/${basename_no_ext}_h265.mp4"
    
    ffmpeg -i "$file" -c:v libx265 -crf 28 -c:a copy -y "$output_file"
done
This bash script creates the destination directory if it doesn't exist, then iterates through all matching files. It strips the original extension and appends _h265.mp4. This method is highly portable and works efficiently on headless servers or local machines.

Handling Edge Cases and Performance

When encoding multiple files, memory usage can spike if you attempt parallel processing. While FFmpeg supports multi-threading via -threads 0 (which uses all available cores), running multiple instances simultaneously can overwhelm your system. It is often safer to run them sequentially unless you have ample RAM and a powerful multi-core processor. If you encounter errors where certain files fail to decode, check the FFmpeg logs for unsupported codecs within those specific containers. Some older AVI files may contain codecs that libx265 cannot easily work with if the container structure is non-standard. In such cases, you may need to transcode to an intermediate format first. For issues related to specific camera formats failing to play after conversion, refer to DV Video from Sony Digital 8 Camera Fails to Play in AVI using FFmpeg with H.265, which discusses similar compatibility pitfalls. Always verify the output files after encoding. Check that the duration matches the source and that audio sync remains intact. If you notice FPS drops or artifacts, adjust the -crf value or try adding -preset medium to balance speed and quality.

Frequently Asked Questions

Can I preserve the original folder structure in the output?

Yes, but it requires more complex scripting. Instead of placing all files in one destination folder, you must calculate the relative path from the source root to the current file and recreate that directory structure in the destination before saving the new file.

What is the best CRF value for H.265 encoding?

A CRF of 28 is widely recommended for a good balance between file size and visual quality. Lower values like 20 provide near-lossless quality but result in much larger files, while higher values like 32 reduce file size significantly but may introduce visible compression artifacts.

How do I skip files that are already encoded?

You can add a check in your script to see if the output file already exists before running FFmpeg. If the output file is present, the script can skip that iteration, saving time and computational resources.

Will copying the audio stream cause quality loss?

No, using -c:a copy performs a stream copy, meaning the audio data is transferred exactly as it is in the source file without re-encoding. This is lossless and very fast.

Is H.265 compatible with all devices?

While H.265 is becoming standard, older devices like early smartphones or some smart TVs may not support it. Always test your encoded files on the target playback devices to ensure compatibility before archiving large batches.

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