FORFILES - CMD


Overview

FORFILES is a command-line utility in Windows used for batch processing a set of files. It allows users to run a specified command on each file in a directory or a set of files matching a criteria. The command is highly useful for management of files based on their modification dates, types, names, and other attributes. Common use cases include deleting old logs, archiving files, and automating updates to file contents.

Syntax

The basic syntax of FORFILES is:

FORFILES [/P pathname] [/M searchmask] [/S] [/C command] [/D [+ | -] {date | days}]
  • /P pathname : Specifies the path to the starting directory.
  • /M searchmask : Searches files according to a wildcard. Default is * which implies all files.
  • /S : Instructs the command to search into subdirectories.
  • /C command : The command to execute for each file. Default is "cmd /c echo @file".
  • /D date : Selects files with a modification date greater than or equal to (+), or older than or equal to (-), the specified date. The date is specified in the format MM-DD-YYYY. If days is used, files modified days before today are selected.

Options/Flags

  • /P – Sets the starting path. If not specified, the current directory is used.
  • /M – Defines the pattern to match against file names. Without this, all files are processed.
  • /S – Includes subdirectories in the search.
  • /C – Specifies the command to run on each file. The command must be enclosed in double quotes. Special variables like @file, @path, @fname, @ext can be used within the command string.
  • /D – Filters files by date. Can use specific dates or relative dates (e.g., -30 for files older than 30 days).

Examples

  1. Delete files older than 30 days:

    FORFILES /P "C:\Logs" /S /D -30 /C "cmd /c del @file"
    
  2. Echo file names with a specific extension:

    FORFILES /M *.txt /P C:\Documents /C "cmd /c echo @file"
    
  3. Archive modified files:

    FORFILES /D +01-01-2023 /C "cmd /c compress @file @file.zip"
    

Common Issues

  • Permission Errors: Make sure you have appropriate permissions to execute commands on the files.
  • Complex Commands: Complex commands need to be correctly formatted and often enclosed in quotes. Missing or unbalanced quotes can cause errors.
  • Date Confusions: Ensure the date format matches MM-DD-YYYY, and relative dates are used correctly with +/- signs.

Integration

FORFILES can be integrated with other CMD tools to create powerful scripts:

FORFILES /S /D -10 /C "cmd /c IF @isdir == FALSE copy @path C:\Backup"

This script finds all non-directory files modified within the last 10 days and copies each to a backup directory.

  • DIR: List directory contents, can be used to gather files before processing.
  • DEL: Delete files, commonly used in conjunction with FORFILES.
  • MOVE: Move files, also often used with FORFILES for organizing files based on date or type.

For more details, consult the official Microsoft documentation on FORFILES.