forfilesFORFILES: delete files older than N days (logs, /d, /c)
Use forfiles /p /m /d /c to delete old log files safely in Windows CMD—date rules, @path quoting, errors, and alternatives vs PowerShell.
forfiles selects files by path, mask, and relative date, then runs a command per match—common pattern: delete log files older than 30 days without custom FOR loops. Typical skeleton: forfiles /p "C:\Logs" /m *.log /d -30 /c "cmd /c del @path" (run elevated if files are protected; test with echo @path first).
Operations teams use this for IIS logs, print spooler trace leftovers, agent diagnostics, and build-server artifact retention. Mistakes—wrong /p, bad /d sign, missing quotes around @path when spaces exist—cause mass deletion incidents; guard with backups, dry runs, and maintenance windows.
You will learn /d semantics (negative = older than N days), substitution tokens (@file, @path, @fsize), defensive scripting, troubleshooting “ERROR: No files found”, and links to FORFILES, DEL, DIR /b.
Core Syntax
FORFILES [/P pathname] [/M mask] [/S] [/C command] [/D [+ | -] {date | days}]
| Switch | Role |
|---|---|
/P | Root path to scan |
/M | File pattern (default *.*) |
/S | Subdirectories |
/D -30 | Files last modified 30+ days ago |
/C | Command to run (default cmd /c echo @file) |
Safer dry run
forfiles /p "C:\Logs" /m *.log /d -30 /c "cmd /c echo @path"
Replace echo with del only after output review.
Examples
Example 1: Delete old .log files (non-recursive)
forfiles /p "C:\App\Logs" /m *.log /d -14 /c "cmd /c del /f /q @path"
Example 2: Include subfolders
forfiles /p "C:\App\Logs" /m *.log /s /d -30 /c "cmd /c del /f /q @path"
Example 3: Archive then delete (two-step pattern)
First copy with ROBOCOPY or compress; then delete—do not chain deletion without retention policy approval.
Example 4: Only large files
forfiles lacks size filter—pre-filter with PowerShell or combine with external tools; mention honestly to avoid false expectations.
Example 5: Scheduled Task
Run under a service account with least privilege that can delete only intended directories—never SYSTEM with a broad C:\ path variable.
Example 6: IIS W3SVC log folders
Point /p at the configured log directory—version-specific—verify C:\inetpub\logs\LogFiles subpaths per site id.
Example 7: Error handling wrapper
Wrap invocation logging >> cleanup.log with timestamp via echo.
Example 8: Positive date selection /D +mm/dd/yyyy
Select files modified on or after date—read forfiles /? carefully; locale affects parsing—test.
Example 9: Substitute @relpath
Handy when presenting relative diagnostics to developers without full UNC exposure in tickets.
Example 10: Pair with if exist guard batch harness
Ensures directory exists before forfiles to avoid ambiguous errors misleading on-call engineers at 3am.
Use Cases
- Log rotation budgets on small business servers without enterprise log tools.
- CI
%TEMP%sweeps for stuck pipeline debris. - Field laptops with disk pressure before imaging refresh.
- Medical imaging workstations (follow retention law—legal holds override scripts).
- VDI gold-image maintenance tooling.
- Developer Docker Desktop log bloat mitigation host-side—not inside containers—distinct path discipline.
- Observability agents debug zip accumulations vendor support generates rapidly.
- Gaming support clearing crash dumps older than retention playful yet real disk savings.
- Retail kiosks purging temporary receipt print spool artifacts on a schedule.
- MSP maintenance windows with customer-specific retention policies documented per tenant.
Tips
- Never point
/patC:\accidentally via variable typo. - Use
/c "cmd /c del /f /q \"@path\""style quoting when paths include spaces—verify on a copy tree. - Monitor Task Scheduler history for exit codes.
- Combine with disk free-space alerting—deletion scripts mask slow growth until another subsystem fails.
Troubleshooting
| Symptom | Fix |
|---|---|
| No files found | Wrong /p, pattern, or date math |
| Access denied | Elevation or ACL adjust |
| Deletes wrong files | Fix mask; run dry run |
| Script “succeeds” but disk unchanged | Files locked—stop service or use move-then-reboot patterns cautiously |
Related Commands
Frequently Asked Questions
Is forfiles built in?
Yes on supported Windows versions for admin automation—still verify forfiles /? on target build.
vs PowerShell Get-ChildItem?
PowerShell is richer (size filters). forfiles shines in locked-down .cmd environments.
Can I delete folders?
forfiles targets files—directories need RMDIR patterns or other tools.
Does /d -7 mean last week?
Approximately 7 days older than current date by last-write timestamp—clocks and timezone matter.
Quick Reference
forfiles /p "C:\Logs" /m *.log /s /d -30 /c "cmd /c del /f /q @path"
Practice
Use the interactive CMD simulator and the commands reference.
Summary
forfiles is a practical, built-in way to age out log and temp files with /d date windows and a /c action. Treat it like any bulk deletion tool: dry-run first, scope paths narrowly, document retention, and match the approach to your backup and compliance requirements so cleanup scripts prevent outages instead of causing them.