Windows CMDInteractive Lab
File Managementforfiles

FORFILES: 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.

Rojan Acharya·
Share

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}]
SwitchRole
/PRoot path to scan
/MFile pattern (default *.*)
/SSubdirectories
/D -30Files last modified 30+ days ago
/CCommand 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

  1. Log rotation budgets on small business servers without enterprise log tools.
  2. CI %TEMP% sweeps for stuck pipeline debris.
  3. Field laptops with disk pressure before imaging refresh.
  4. Medical imaging workstations (follow retention law—legal holds override scripts).
  5. VDI gold-image maintenance tooling.
  6. Developer Docker Desktop log bloat mitigation host-side—not inside containers—distinct path discipline.
  7. Observability agents debug zip accumulations vendor support generates rapidly.
  8. Gaming support clearing crash dumps older than retention playful yet real disk savings.
  9. Retail kiosks purging temporary receipt print spool artifacts on a schedule.
  10. MSP maintenance windows with customer-specific retention policies documented per tenant.

Tips

  • Never point /p at C:\ 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

SymptomFix
No files foundWrong /p, pattern, or date math
Access deniedElevation or ACL adjust
Deletes wrong filesFix mask; run dry run
Script “succeeds” but disk unchangedFiles 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.