sábado, 24 de fevereiro de 2018

Eliminar pasta e arquivos automaticamente .BAT


Temos um servidor que faz backups diáriosdas bases de dados SQL  para o disco, para uma determinada pasta.
Ora, os ficheiros vão incrementando diariamente a não ser que se eliminem os mais antigos. E se essa eliminação puder ser colocada num batch file para ser executado automaticamente muito melhor.
A primeira tentativa foi verificar o comando de MS-DOS Delete ou  Erase. Nenhum dos dois tem possibilidades de calendarização. Pesquisando um pouco mais encontrei o comando ForFiles.exe.
Este comando existe por default nos servidores e pode também ser instalado nos desktops. O windows 7 já o tem incorporado.
Numa janela de MS-DOS poderemos ver as possibilidades deste comando:
C:\>forfiles /?
FORFILES [/P pathname] [/M searchmask] [/S]  [/C command] [/D [+ | -] {MM/dd/yyyy | dd}]
Description:
    Selects a file (or set of files) and executes a command on that file. This is helpful for batch jobs.
Parameter List:
    /P    pathname      Indicates the path to start searching.
                        The default folder is the current working  directory (.).
    /M    searchmask    Searches files according to a searchmask. The default searchmask is ‘*’ .
    /S                  Instructs forfiles to recurse into  subdirectories. Like “DIR /S”.
    /C    command       Indicates the command to execute for each file.
                        Command strings should be wrapped in double  quotes.
                        The default command is “cmd /c echo @file”.
                        The following variables can be used in the  command string:
                        @file    – returns the name of the file.
                        @fname   – returns the file name without extension.
                        @ext     – returns only the extension of the file.
                        @path    – returns the full path of the file.
                        @relpath – returns the relative path of the file.
                        @isdir   – returns “TRUE” if a file type is a directory, and “FALSE” for files.
                        @fsize   – returns the size of the file in bytes.
                        @fdate   – returns the last modified date of the file.
                        @ftime   – returns the last modified time of the file.
                        To include special characters in the command line, use the hexadecimal code for the character
                        in 0xHH format (ex. 0x09 for tab). Internal  CMD.exe commands should be preceded with
                        “cmd /c”.
    /D    date          Selects files with a last modified date greater  than or equal to (+), or less than or equal to
                        (-), the specified date using the”MM/dd/yyyy” format; or selects files with a  last modified date greater than or equal to (+)  the current date plus “dd” days, or less than or  equal to (-) the current date minus “dd” days. A  valid “dd” number of days can be any number in   the range of 0 – 32768.  “+” is taken as default sign if not specified.
    /?                  Displays this help message.
Examples:
    FORFILES /?
    FORFILES
    FORFILES /P C:\WINDOWS /S /M DNS*.*
    FORFILES /S /M *.txt /C “cmd /c type @file | more”
    FORFILES /P C:\ /S /M *.bat
    FORFILES /D -30 /M *.exe
             /C “cmd /c echo @path 0x09 was changed 30 days ago”
    FORFILES /D 01/01/2001
             /C “cmd /c echo @fname is new since Jan 1st 2001”
    FORFILES /D +7/10/2013 /C “cmd /c echo @fname is new today”
    FORFILES /M *.exe /D +1
    FORFILES /S /M *.doc /C “cmd /c echo @fsize”
    FORFILES /M *.txt /C “cmd /c if @isdir==FALSE notepad.exe @file”
No meu caso, para eliminar ficheiros de backup antigos, mais velhos que seis dias, utilizo o comando desta forma:
forfiles /P “F:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup” /S /M *.bak /D -6 /C “cmd /c del @PATH”
em que:
F:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup –> diretório onde tenho backups diários e desejo eliminar os ficheiros.
*.bak –> tipo de ficheiros a eliminar, neste caso todos que terminem em bak.
/D -6 –> eliminar ficheiros anteriores a seis dias, ou seja, quero preservar sempre os últimos 5 backups.
cmd /c del @PATH –> eliminar os ficheiros
Por fim, basta colocar este comando num batch file (ficheiro de texto com terminação bat) e fazer uma calendarização com a ferramenta do windows “Scheduled Tasks” presente nas “System Tools“.
Outro Ex:
echo  eliminando 8 dias atraz...
forfiles -p "C:\BACKUP\FULL & DIFF" -d -8 -s -m *.*  -c "cmd /c del /f /q @path"

echo eliminando 20 dias atraz...
forfiles -p "C:\BACKUP" -d -20 -s -m *.zip  -c "cmd /c del /f /q @path"

Nenhum comentário: