Forfiles is a useful windows command to select a set of files and then run a command on each of the files. It’s similar to the functionality of find command on Linux OS.
The syntax of the forfiles is as follows.
forfiles <Criteria to select files> /C "command to be applied on each of the files selected"
The criteria we can use to select the files:
Modified date or Number of days it was last modified from (option /D)
Search files based on name(option /M)
Look for files in subdirectories also (option /S)
Look for files in a specific directory (option /P)
We can use any combination of the above to select the required files.
Find all excel files modified 10 days back in the current folder and subfolders
forfiles /D -10 /S /M *.xlsx /C "cmd /c echo @path"
In the above command @path is used to print the complete absolute path of the file. Similarly we can use below variables in the command part.
@file – Name of the file(includes extension)
@fname – Name of the file excluding extension
@relpath – Relative path of the file from current folder
@ext – Extension of the file
@fsize – Size of the file
@fdate – Last modified date of the file
@ftime – Last modified time of the file
delete all log files created in the last 1 month
forfiles /D +30 /S /M *.log /C "cmd /c del @file"
Copy/Backup files modified after 1st Jauary 2015
forfiles /D 01/01/2015 /M * /C "cmd /c copy @file D:\backupFolder\"
Get list of all picture files with their size
forfiles /S /M *.jpg /C "cmd /c echo @path @fsize"
This command searches pictures of only jpg type. To search picture of different file type(jpeg, png etc), the command has to be triggered again.
Get list of all exe’s and their last modified date
forfiles /M *.exe /C "cmd /c echo @path @fdate"
c:\Windows>forfiles /M *.exe /C "cmd /c echo @path @fdate" "c:\Windows\bfsvc.exe" 11/20/2010 "c:\Windows\explorer.exe" 2/24/2011 "c:\Windows\fveupdate.exe" 7/13/2009 "c:\Windows\HelpPane.exe" 7/13/2009 "c:\Windows\hh.exe" 7/13/2009 "c:\Windows\notepad.exe" 7/13/2009 "c:\Windows\regedit.exe" 7/13/2009 "c:\Windows\splwow64.exe" 2/10/2012 "c:\Windows\twunk_16.exe" 6/10/2009 "c:\Windows\twunk_32.exe" 7/13/2009 "c:\Windows\winhlp32.exe" 7/13/2009 "c:\Windows\write.exe" 7/13/2009
Rename file extensions using forfiles command
Read this: Rename File extensions in bulk
List all sub-directories in a given folder
If you want to print all the subdirectories in the current directory
forfiles /m * /c "cmd /c if @isdir==TRUE echo @file"