martes, 28 de mayo de 2013

Comando FORFILES, acciones sobre múltiples ficheros




En Windows Vista, W7 y las versiones Server de 2008 en adelante, han incluido un nuevo comando a la shell (línea de comandos) que parece bastante interesante para automatizar tareas sobre ficheros.

Un ejemplo de cómo usar el siguiente comando, puede ser el siguiente script:


Set _Source=Ruta de la que borrar los ficheros “C:/temp”

Se borran los ficheros (/C if @isdir==TRUE RD /Q @path) que tengas más de diez días de antigüedad (/D -10). Que se encuentren en el Path indicado por la ruta _Source (/P), haciendo la búsqueda recursiva (/S ir a subFolders) con cualquier mascara (/M *)

Forfiles /P "%_Source%" /S /M * /D -10 /c "cmd /C if @isdir==TRUE RD /Q @path"
echo *Para ver el resultado y no dejar que el script se vaya de la ventana, poner rem por
echo *delante para quitarlo si no queremos interacción de usuario o borrarlo directamente.
pause
exit

Si ponemos todo seguido en el cmd, también podemos ejecutarlo en una única instrucción para probarlo.
La sintaxis es la siguiente (en inglés):

FORFILES [/p Path] [/m Mask] [/s] [/c Command] [/d [+ | -] {dd/MM/yyyy | dd}]  
 Key
   /p Path      The Path to search  (default=current folder)
   /s           Recurse into sub-folders
   /C command   The command to execute for each file.
                Wrap the command string in double quotes.
                Default = "cmd /c echo @file"
                The Command variables listed below can also be used in the
                command string.
   /D date      Select files with a last modified date greater than or
                equal to (+), or less than or equal to (-),
                the specified date using the "dd/MM/yyyy" format;
   /D + dd      Select files with a last modified date greater than or
                equal to the current date plus "dd" days. (in the future)
   /D - dd      Select files with a last modified date less than or
                equal to the current date minus "dd" days. (in the past)
                A valid "dd" number of days can be any number in
                the range of 0 to 32768.   (89 years)
                "+" is taken as default sign if not specified.

   Command Variables:
      @file    The name of the file.
      @fname   The file name without extension.               
      @ext     Only the extension of the file.                 
      @path    Full path of the file.
      @relpath Relative path of the file.         
      @isdir   Returns "TRUE" if a file type is a directory,
               and "FALSE" for files.
      @fsize   Size of the file in bytes.
      @fdate   Last modified date of the file.
      @ftime   Last modified time of the file.

No hay comentarios:

Publicar un comentario