Windows command(forfiles)

Reference:

  1. Forfiles
  2. forfiles指令
  3. 用批處理文件自動備份文件及文件夾,並自動刪除n天前的文件
  4. 7z command

Example: Backup file into archive file based on 7z and forfiles.

The command as below.

FORFILES /P D:\SourceDir /S -D -10 /C "CMD /C ECHO @path" > D:\Backup\filelist.txt
"D:\BackUp\7-Zip\7z.exe" a -sdel -spf2 D:\BackupDir\DataLog_BackupAt%date:~0,4%%date:~5,2%%date:~8,2%.zip @D:\Backup\filelist.txt
del D:\Backup\filelist.txt

Step1:

Find all files modified 10 days back in the D:\SourceDir folder and subfolder.

And then, write all files path into D:\Backup\filelist.txt

Step2:

Use 7z.exe to backup and compress files from D:\Backup\filelist.txt to D:\BackupDir\DataLog_BackupAt20110127.zip

After backup these file, these files were be deleted.

(If today is 2011-01-27)

Step3:

delete D:\Backup\filelist.txt


Command and Parameter explanation:

1. FORFILES:

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)

Example: Find all excel files modified 10 days back in the current folder and subfolder.

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

2. Windows command(%date%)

Get date from batch file

3. 7z command

  • Command a. You can use the "a" command with the single letter a. This command stands for "archive" or "add." Use it to put files in an archive.
  • -sdel: delete files after archive

  • -spf2: ???

results matching ""

    No results matching ""