CMD Simulator
File Managementforfiles

FORFILES Command Guide - Select Files and Run Commands in Windows

Learn how to use the forfiles command to select files by criteria and run commands on each in Windows CMD. Includes syntax, examples, and batch scripting use cases.

Rojan Acharya··Updated Mar 18, 2026
Share

The forfiles command is a Windows Command Prompt utility that selects one or more files based on criteria (path, search mask, date) and runs a specified command on each file. Use /P for path, /M for wildcard pattern, and /C for the command to execute. System administrators and scripters use forfiles for batch file processing, log cleanup, and automated file maintenance.

Whether you're deleting files older than 30 days, renaming batches of files, or running a custom command on every file matching a pattern, forfiles provides a built-in alternative to writing complex FOR loops. It supports variable substitution (e.g., @file, @path, @fname) so your command can reference each file's properties.

This comprehensive guide covers forfiles syntax, all parameters and variable placeholders, practical examples for common scenarios, troubleshooting tips, and frequently asked questions. By the end, you'll confidently automate file operations from the command line.

What Is the Forfiles Command?

The forfiles command has been part of Windows since Windows Vista and is available in Windows 10, Windows 11, and Windows Server. It acts as a file iterator: you specify where to look (/P), what to match (/M), optionally when (/D), and what to run (/C). Forfiles executes the command once per matching file, passing file metadata via placeholders.

Forfiles runs in Command Prompt (CMD) and requires no special privileges for most operations. It works with local paths, UNC paths, and mapped drives. The command is particularly useful for scheduled tasks that perform routine file maintenance such as log rotation or temporary file cleanup.

Forfiles Command Syntax

FORFILES [/P path] [/M searchmask] [/S] [/C command] [/D [+|-] date]

Parameters and Switches

ParameterDescription
/P pathPath to search (default: current directory)
/M searchmaskSearch mask/wildcard (default: .)
/SSearch subdirectories recursively
/C commandCommand to run for each file (default: "cmd /c echo @file")
/D dateSelect files by date: +date (modified on/after), -date (modified on/before), or exact date

Variable Placeholders (use in /C command)

PlaceholderDescription
@fileFile name only
@fnameFile name without extension
@extFile extension only
@pathFull path of the file
@relpathRelative path
@isdirTRUE if directory, FALSE if file
@fsizeFile size in bytes
@fdateFile date
@ftimeFile time

Practical Forfiles Command Examples

List All Files in Current Directory

To list files using the default command (echo @file):

forfiles

Expected Output:

"readme.txt"
"config.ini"

Explanation: Without parameters, forfiles selects all files (.) in the current directory and echoes each filename. Useful for quick verification of file presence.

List Files in a Specific Path

To search a specific directory:

forfiles /P C:\Logs /M *.*

Explanation: /P C:\Logs specifies the path; /M *.* matches all files. The default command echoes each filename. Use this to audit files in a target folder.

List Only Text Files

To match files with a specific extension:

forfiles /P C:\Data /M *.txt

Explanation: /M *.txt limits matches to .txt files. Combine with /P to target a specific folder. Essential for extension-based file operations.

List Only Log Files

To match log files by extension:

forfiles /P C:\Windows\Logs /M *.log

Explanation: Common pattern for log management. Use before implementing log rotation or cleanup to verify which files would be affected.

Run a Custom Command on Each File

To execute a command for each matching file:

forfiles /P C:\Temp /M *.tmp /C "cmd /c echo Processing @file"

Explanation: /C specifies the command. Use @file to reference the current filename. The command runs in a new cmd instance per file (cmd /c).

Delete Files Older Than 7 Days

To remove old files (use with caution):

forfiles /P C:\Temp /M *.* /D -7 /C "cmd /c del @path"

Explanation: /D -7 selects files modified 7 or more days ago. The command deletes each. Test with echo @path first to verify targets before using del.

List Files Modified Today

To find files modified on or after a specific date:

forfiles /P C:\Backups /M *.* /D +2026-03-18

Explanation: /D +date selects files modified on or after the date. Use MM-DD-YYYY format. Helpful for backup verification.

Display Full Path for Each File

To show complete path instead of just filename:

forfiles /P C:\Projects /M *.cs /C "cmd /c echo @path"

Explanation: @path gives the full path. Use when you need absolute paths for scripting or logging.

Get File Name Without Extension

To work with base names:

forfiles /P C:\Images /M *.jpg /C "cmd /c echo @fname"

Explanation: @fname strips the extension. Useful when generating new filenames or matching without extension.

Copy Each File to Another Location

To copy matching files (requires xcopy or copy in command):

forfiles /P C:\Source /M *.docx /C "cmd /c copy @path C:\Destination\"

Explanation: Each file is copied to the destination. Ensure the destination exists. Use xcopy for directory structures.

Dry Run Before Deleting Old Logs

To preview files that would be deleted:

forfiles /P C:\Logs /M *.log /D -30 /C "cmd /c echo Would delete: @path"

Explanation: Replace echo with del only after verifying the list. Essential safety step before destructive operations.

Process Files in Subdirectories

To search recursively (if supported):

forfiles /P C:\Data /S /M *.bak /C "cmd /c echo @path"

Explanation: /S includes subdirectories. Verify behavior on your Windows version—recursion support can vary.

Common Use Cases for the Forfiles Command

  1. Log file cleanup – Delete or archive log files older than N days to prevent disk fill. Use /D -30 for 30-day retention with /C "cmd /c del @path" after testing.

  2. Temporary file removal – Schedule forfiles to clear temp directories: forfiles /P C:\Windows\Temp /M *.* /D -7 /C "cmd /c del @path".

  3. Backup verification – List files modified today to confirm backup jobs ran: forfiles /P D:\Backups /M *.* /D +%date%.

  4. Batch rename preparation – List files with @fname and @ext to plan rename logic before implementing in a script.

  5. File count auditing – Use forfiles with a command that increments a counter or logs to a file for compliance reporting.

  6. Pre-migration file inventory – Export list of files matching criteria before migrating: forfiles /P C:\Data /M *.pdf /C "cmd /c echo @path" > pdf-list.txt.

  7. Scheduled archive – Move (copy then delete) old files to archive storage using forfiles with xcopy and del in the command.

  8. Duplicate detection – Run a checksum or comparison tool on each file via /C for duplicate detection workflows.

  9. Thumbnail or preview generation – For images, run a conversion or thumbnail tool on each file via /C.

  10. Configuration file updates – Apply a search-replace or transform tool to each config file matching a pattern.

  11. License or watermark injection – For documents or images, run a tool that adds metadata to each file.

  12. Integration with CI/CD – Use forfiles in build scripts to process generated artifacts (e.g., run a validator on each output file).

Tips and Best Practices

  1. Always test with echo first – Before using destructive commands like del, run with echo @path to verify which files match. Saves accidental data loss.

  2. Use full paths for /P – Specify complete paths to avoid ambiguity: forfiles /P C:\Logs not forfiles /P Logs.

  3. Quote paths with spaces – If path or command has spaces, use quotes: forfiles /P "C:\Program Files\Logs" /C "cmd /c echo @file".

  4. Handle empty results – If no files match, forfiles may exit without output. Check exit code in scripts and handle "no files" case.

  5. Avoid special characters in /C – Complex commands with &, |, or > may need careful escaping. Consider wrapping in a batch file and calling that.

  6. Use /D for date-based operations – Date selection is forfiles' strength. Use -N for "older than N days" in cleanup tasks.

  7. Combine with Task Scheduler – Schedule forfiles for routine cleanup. Run during low-usage periods to avoid locking files in use.

  8. Document your commands – Forfiles syntax can be cryptic. Add comments in batch files explaining the logic.

  9. Consider robocopy for moves – For complex move/archive scenarios, robocopy with /MINAGE may be more robust than forfiles + move.

  10. Verify recursion behavior/S support varies. Test on your Windows version before relying on subdirectory search.

Troubleshooting Common Issues

"ERROR: Invalid directory"

Problem: Forfiles returns "ERROR: Invalid directory" when specifying a path.

Cause: Path does not exist, typo in path, or insufficient permissions.

Solution: Verify path with DIR path. Use cd to navigate and forfiles /P . for current directory. Ensure you have read access to the directory.

Prevention: Use IF EXIST in batch scripts to check path before calling forfiles.

No Files Found When Files Exist

Problem: Forfiles reports no files or produces no output when files are present.

Cause: Search mask /M may not match. Default is .; check extension case or pattern. Path may be wrong.

Solution: Use DIR /B path\*.ext to verify files exist. Try forfiles /M *.* for broadest match. Check path with CD /D path first.

Prevention: Test with DIR and simple forfiles (no /C) before adding complex commands.

Command in /C Not Executing

Problem: The command specified in /C doesn't run or produces errors.

Cause: Syntax error in command, missing cmd /c, or special character escaping issues.

Solution: Ensure command is: cmd /c "your command". Use echo @file as minimal test. For complex commands, put logic in a batch file and call it: cmd /c mybatch.bat @path.

Prevention: Start with simple echo @file, then add complexity incrementally.

Forfiles Not Found

Problem: "forfiles is not recognized" when running the command.

Cause: Forfiles is not in PATH, or you're on an older Windows version (pre-Vista).

Solution: Use full path: C:\Windows\System32\forfiles.exe. Verify with WHERE forfiles. On older Windows, use FOR loop or PowerShell as alternative.

Prevention: Document Windows version requirements. Forfiles is in System32 on Vista and later.

Access Denied When Deleting

Problem: Forfiles runs but del fails with "Access denied" for some files.

Cause: Files in use, read-only attribute, or insufficient permissions.

Solution: Close applications using the files. Run CMD as Administrator. Use attrib -r @path before del if read-only. For in-use files, consider running during maintenance window.

Prevention: Use attrib -r in the command for read-only files: cmd /c attrib -r @path & del @path.

Date Format Errors with /D

Problem: /D parameter doesn't work or selects wrong files.

Cause: Date format may be locale-dependent. Use MM-DD-YYYY. + and - have specific meanings.

Solution: Use +MM-DD-YYYY for "on or after," -MM-DD-YYYY for "on or before." For "older than N days," use -N (e.g., -7 for 7 days ago). Test with echo @path first.

Prevention: Document date format in scripts. Use %date% in batch for dynamic dates, but ensure format is correct.

Related Commands

FOR – Loop Construct

FOR is the classic CMD loop for iterating over files, directories, or strings. Use FOR for more flexibility and complex logic; use forfiles for simpler, date-based selection.

When to use forfiles: Date-based selection, quick one-liners, built-in variable substitution. When to use FOR: Complex conditions, parsing, or when forfiles isn't available.

DEL / ERASE – Delete Files

DEL deletes files. Often used inside forfiles /C for cleanup: forfiles /P C:\Temp /M *.* /D -7 /C "cmd /c del @path".

When to use forfiles + del: Selective deletion by date or pattern. Forfiles selects; del performs the delete.

XCOPY / ROBOCOPY – Copy Files

XCOPY and ROBOCOPY copy files with optional date filters. ROBOCOPY has /MINAGE and /MAXAGE for date-based copy. Use forfiles when you need to run a custom command per file; use robocopy for bulk copy with date filters.

When to use forfiles: Custom command per file (e.g., transform, validate). When to use robocopy: Bulk copy/mirror with date or attribute filters.

DIR – List Files

DIR lists directory contents. Use DIR to verify files exist before forfiles, or to get a simple list. Forfiles adds command execution per file.

When to use DIR: Quick listing, verification. When to use forfiles: Execute a command on each file.

PowerShell Get-ChildItem

Get-ChildItem (or dir in PowerShell) with ForEach-Object provides similar functionality in PowerShell with more flexibility. Use forfiles in CMD/batch; use PowerShell for complex scripting.

When to use forfiles: Batch scripts, CMD environment, simple iteration. When to use PowerShell: Complex logic, object pipeline, .NET integration.

Frequently Asked Questions

What does the forfiles command do?

Forfiles selects files based on path, search mask, and optional date criteria, then runs a specified command on each file. It supports variable placeholders like @file, @path, @fname so the command can reference each file's properties.

How do I delete files older than 30 days with forfiles?

Use: forfiles /P C:\Path /M *.* /D -30 /C "cmd /c del @path". Replace C:\Path with your target. Test first with echo @path instead of del @path to verify which files would be deleted.

What is the difference between forfiles and FOR?

FOR is a general-purpose loop; forfiles is a dedicated file iterator with built-in date selection and variable substitution. Forfiles simplifies date-based file operations; FOR offers more flexibility for custom logic.

Can forfiles search subdirectories?

Forfiles supports /S to search subdirectories on some Windows versions. Behavior can vary—test on your system. For guaranteed recursion, use a FOR /R loop or PowerShell.

What variable placeholders does forfiles support?

Forfiles supports @file (filename), @fname (name without extension), @ext (extension), @path (full path), @relpath (relative path), @isdir (TRUE/FALSE), @fsize (size), @fdate (date), @ftime (time). Use these in the /C command.

How do I run forfiles on a network path?

Use UNC path: forfiles /P \\server\share\folder /M *.*. Ensure you have read access. For network paths, test with DIR first to verify connectivity.

Why does forfiles return "Invalid directory"?

The path in /P doesn't exist or isn't accessible. Verify with DIR path. Use full paths and ensure no typos. Check permissions if it's a network or system path.

Can forfiles run PowerShell commands?

Yes, invoke PowerShell from the command: forfiles /P C:\Data /M *.ps1 /C "cmd /c powershell -File @path". Or use powershell -Command for inline scripts. Ensure PowerShell is in PATH.

How do I use forfiles in a scheduled task?

Create a batch file that runs forfiles, then schedule the batch file with Task Scheduler. Set appropriate user account and run time. Use full paths in the batch file.

What is the default command if I omit /C?

The default is cmd /c echo @file, which echoes each filename. So forfiles alone lists files in the current directory.

Can forfiles handle paths with spaces?

Yes, use quotes: forfiles /P "C:\Program Files\Logs" /M *.log /C "cmd /c echo @file". Quote both path and command when they contain spaces.

Is forfiles available on all Windows versions?

Forfiles is available from Windows Vista onward, including Windows 10, 11, and Server. It is not available on Windows XP. Use FOR loops or PowerShell on older systems.

Quick Reference Card

CommandPurposeExample Use Case
forfilesList files in current dirQuick file listing
forfiles /P C:\Logs /M *.logList log files in pathLog audit
forfiles /P C:\Temp /M *.* /D -7Files older than 7 daysCleanup preview
forfiles /P C:\Data /M *.txt /C "cmd /c echo @path"Echo full path per filePath listing
forfiles /P C:\Temp /M *.* /D -30 /C "cmd /c del @path"Delete files older than 30 daysLog rotation
forfiles /P C:\Backup /M *.* /D +2026-03-18Files modified todayBackup verification
forfiles /M *.bak /C "cmd /c echo @fname"Names without extensionRename planning

Try the Forfiles Command in Our Simulator

Practice the forfiles command safely in our Windows Command Simulator. Run forfiles, forfiles /P C:\ /M *.txt, and other examples in your browser. Perfect for learning file iteration and testing commands before production use.

Visit the Commands Reference for a full list of supported Windows CMD commands, including file management, directory operations, and automation utilities.

Summary

The forfiles command is a powerful Windows utility for selecting files and running commands on each. Use /P for path, /M for search mask, /D for date-based selection, and /C for the command. Variable placeholders like @file, @path, and @fname let your command reference each file's properties.

Key use cases include log cleanup, temporary file removal, backup verification, batch processing, and scheduled maintenance. Always test with echo @path before destructive operations like delete. Combine forfiles with Task Scheduler for automated file management.

For related tasks, use FOR for complex loops, DEL for deletion, ROBOCOPY for bulk copy with date filters, and PowerShell for advanced scripting. Master forfiles to streamline file automation from the command line.