How to archive files older than 7 days with creating one archive for all files with same date? - date

I am looking for someone who can help me make a scheduled task to automatically move log files into RAR archives.
It does not have to be a batch file solution, if you have other ideas please share.
I got the basic code for it. This is the batch file code I have so far:
"C:\Program Files\WinRAR\rar.exe" a -ag -ms "D:\tet\Web3811\Web3811\LogsBackup\" #backup.txt
That line in the batch file runs RAR to create an archive with all files in the folder specified in list file backup.txt containing:
D:\tet\Web3811\Web3811\log
The RAR archive is created in D:\tet\Web3811\Web3811\LogsBackup\ with yyyy-mm-dd.rar as file name.
I need help with:
The RAR archives should have date in format dd-mm-yyyy in name instead of yyyy-mm-dd.
Only log files should be archived which are older than 7 days according to last modification date in comparison to current date whereby time does not matter, just date. All files with a date and time before 27-07-2014 00:00:00 should be added to the RAR archives if current date and time is 02-08-2014 12:30:00.
Each RAR archive to create should contain only files with same last modification date.
All archived log files should be deleted once the RAR compression is completed without errors.
The reason for being a batch file is the requirement of being executable as scheduled task.
An example for third requirement:
The folder contains 5 log files with following last modification dates:
Oldest.log 23-07-2014 02:20:54
AlsoOld.log 23-07-2014 23:52:26
Sample1.log 25-07-2014 09:08:46
Sample2.log 25-07-2014 12:59:02
Newest.log 26-07-2014 18:32:48
The scheduled task needs to create 3 archives with following names and files:
23-07-2014_Logs.rar with Oldest.log and AlsoOld.log.
25-07-2014_Logs.rar with Sample1.log and Sample2.log.
26-07-2014_Logs.rar with just Newest.log.
No log file was created on 24-07-2014 and therefore also no RAR archive to create for this day.

I suggest to use in the batch file:
"C:\Program Files\WinRAR\rar.exe" mf -ac -ao -agDD-MM-YYYY-NN -ep1 -idq -m5 -to7d -y "D:\tet\Web3811\Web3811\LogsBackup\Logs_" #backup.txt
Above command moves all files older than 7 days according to last modification date into a RAR archive with name starting with Logs_ and current date in requested format and an additional incrementing number starting with number 1 after a hyphen in case of running this command line several times on one day.
Only files with archive attribute are moved into an archive. The archive attribute is cleared after archiving a file even if deletion is not possible for example when another application has opened the file with a write lock. RAR does not delete files on which reading and compressing the data failed at all (read lock).
See text file Rar.txt in program files folder of WinRAR for a description of all the switches used in this command line.
After some requirements have been explained better, here is a batch file to create the archive files as finally requested.
#echo off
setlocal EnableExtensions EnableDelayedExpansion
rem Define the directories to use for backup task.
set "LogDirectory=D:\tet\Web3811\Web3811\log"
set "BakDirectory=D:\tet\Web3811\Web3811\LogsBackup"
rem Get all file names in log directory into a list file sorted by last
rem modification date with oldest file at top and newest at bottom.
rem Note: /S is important to get the file names with complete path.
dir "%LogDirectory%\*" /A-D /B /OD /S /TW 1>"%BakDirectory%\LogFiles.lst" 2>nul
rem Jump to clean up stage if no file found in the log directory.
if errorlevel 1 goto :CleanUp
rem Delete list file for all files with same day if file exists
rem for example from a previous execution of this batch file
rem which was terminated manually by a user during execution.
if exist "%BakDirectory%\DayFiles.lst" del "%BakDirectory%\DayFiles.lst"
set LastDate=none
for /F "usebackq delims=" %%F in ( "%BakDirectory%\LogFiles.lst" ) do (
set FileTime=%%~tF
rem Get just file date from file time in format DD-MM-YYYY.
rem The file time string format depends on date and time
rem format definition in Windows language settings.
rem Therefore the line below must be adapted if date format
rem is whether DD.MM.YYYY nor DD-MM-YYYY nor DD/MM/YYYY.
set FileDate=!FileTime:~0,2!-!FileTime:~3,2!-!FileTime:~6,4!
rem Is the last modification date of this file different
rem to last modification date of the previous file?
if not "!FileDate!"=="!LastDate!" (
rem Nothing to archive on first difference.
if not "!LastDate!"=="none" call :ArchiveLogs
rem Exit loop if RAR has not archived any file which means
rem all other files are modified within the last 7 days.
if "!LastDate!"=="ExitLoop" goto CleanUp
rem Start creating a new list.
set LastDate=!FileDate!
)
rem Append name of this file with path to current day list.
echo %%F>>"%BakDirectory%\DayFiles.lst"
)
rem Jump to clean up stage if no list file with files to archive.
if not exist "%BakDirectory%\DayFiles.lst" goto CleanUp
rem Otherwise with no log file created or modified within
rem the last 7 days, but at least one older file exists
rem nevertheless, archive all those files in list file.
call :ArchiveLogs
:CleanUp
del "%BakDirectory%\LogFiles.lst"
endlocal
goto :EOF
:ArchiveLogs
rem Move all files in the list file older than 7 days without
rem path using best compression into a RAR archive with last
rem modification date of archived file(s) in RAR file name.
"C:\Program Files\WinRAR\Rar.exe" mf -ep1 -idq -m5 -to7d -y "%BakDirectory%\!LastDate!_Logs.rar" "#%BakDirectory%\DayFiles.lst"
rem Exit FOR loop above if no file archived because
rem no file in the list file is older than 7 days.
if errorlevel 10 set LastDate=ExitLoop
del "%BakDirectory%\DayFiles.lst"
I first thought, it is not possible to do this without coding a small console application to create the file lists per date and ignore files not modified within the last 7 days. But then I had an idea on how to solve this main problem using just a batch file and RAR as it can be seen above.
It is best to run this batch file with a scheduled task short after midnight as RAR takes also current time into account for "older than 7 days" and not just the date.
But it would be no problem if batch file is executed for example at 18:00 and there are log files created respectively modified at 23:00. In this case log files with last modification date before 18:00 and with a date exactly before 7 days in comparison to current date are moved first into a RAR archive, and on next day the other log files last modified after 18:00 from same date are moved also to the RAR archive for this date.
Example with batch task executed always at 18:00 and what happens.
There are the log files
FirstSundayAugust2014_1.log 03/08/2014 15:23
FirstSundayAugust2014_2.log 03/08/2014 23:48
and the scheduled task runs on Sunday, 10th August 2014 at 18:00.
The batch file moves FirstSundayAugust2014_1.log into RAR archive 03-08-2014_Logs.rar, but the other log file FirstSundayAugust2014_2.log also from last Sunday remains in the directory.
On Monday, 11th August 2014 at 18:00 the batch file moves also FirstSundayAugust2014_2.log into the RAR archive 03-08-2014_Logs.rar and this archive contains now both log files created respectively last modified on first Sunday in August 2014.
One more note:
RAR file names with date in format DD-MM-YYYY are not really good in my point of view. Better would be YYYY-MM-DD as this results in *.rar files where those RAR files listed alphabetically according to file name in Windows Explorer would result in same list as when those RAR files are listed according to file date/time in Windows Explorer.
To get RAR files with format YYYY-MM-DD for the date in file name the line
set FileDate=!FileTime:~0,2!-!FileTime:~3,2!-!FileTime:~6,4!
needs to be modified to
set FileDate=!FileTime:~6,4!-!FileTime:~3,2!-!FileTime:~0,2!

Related

Copy a folder and create a new folder for each month

I have very little experience programming, so I'm not not sure if the following can be done.
I need to copy files from a folder and put them into another location for backup. I would like to copy the folder once a month and put the files into a backup folder labeled for that month and year.
My source folder is C:\Users\Company Name\Documents\Global S Programs
My destination folder is I:\Quality\CMM Global S programs\
Thanks
I found this simple code to copy the files, create a new folder, label it with the current date and year and then paste the files into it.
Than I just set up the task scheduler to run it once a month.
I ended up changing the order of the date to MMDDYYYY.
To get MMDDYYYY change line 6 to this "ds=%%B_%%C_%%A"( %%A=Year %%B=Month %%C=Day)
#Echo Off
Set "sd=C:\Users\Company Name\Documents\Global S Programs"
Set "dd=I:\Quality\CMM Global S programs"
If Not Exist "%sd%\" Exit /B
For /F "Tokens=1-3Delims=/ " %%A In ('RoboCopy/NJH /L "\|" Null'
M D Year
) Do If Not Defined ds Set "ds=%%A_%%B_%%C"
If Not Defined ds Exit /B
RoboCopy "%sd%" "%dd%\%ds%" /E

Which commands to use to extract and reconstruct multivolume archives using .rev files on CentOS 6.x?

Which commands can be used to extract & reconstruct multivolume RAR archives with missing parts using .rev files in Centos 6.x?
I have many RAR archives split into many parts:
dbzdv1
part01.rar
part02.rar
part03.rar
...
dbzdv2
part01.rar
part02.rar
part03.rar
...
Screenshot of files of a multivolume archive http://imageshack.com/a/img633/5450/ekUKTd.png
All volumes are protected with same password.
1. I want extract with a single command all protected multivolume RAR archives
Every RAR archive is split into many parts.
2. The .rev file should be used to automatically reconstruct a missing part.
3. I shoud have folders with files inside after extraction.
folder1
folder2
folder3
I want compress with RAR with a single command all those folders into separate archives:
folder1.rar
folder2.rar
folder3.rar
4. I want get a multivolume RAR archive with no compression and automatically tested on errors if an extracted folder is very large.
folder1 --> folder1.part01.rar
folder2.part02.rar
Problems:
If I try using this command to extract a volume:
unrar e dbzdv1.part01.rar
Shortly after start in terminal I'm asked for password for every part, not just once for the entire multivolume archive. I don't want to type password for 100-500 parts.
If I try using WinRAR on Wine and open files the error Not enough memory is output.
Screenshot of files of winrar-wine error http://imageshack.com/a/img913/2331/n6LOtl.png
Introduction
I'm not using CentOS and therefore all my answers are not verified on this operating system.
WinRAR is installed usually on Windows with 3 executables:
GUI version WinRAR.exe supporting compression in RAR and ZIP format and even more common archive formats for extraction (shareware).
Console version Rar.exe supporting compression and extraction of RAR archives only (shareware).
Console application UnRAR.exe for extraction of RAR archives only (free, no license needed).
In program files folder of WinRAR there is additionally the text file Rar.txt which is the manual for the console version Rar. GUI Version WinRAR supports nearly same set of switches, but there are some differences like -af<type> supported only by GUI version. The complete list of switches for WinRAR can be found in help on page Alphabetic switches list (Contents - Command line mode - Switches). Rar and UnRAR output both a short help with listing all supported commands and switches if executed in a command prompt window without any parameter.
Extraction from several password protected multivolume archives
The switch -p[pwd] can be used on command line to extract files from a password protected archive of any type as explained for example in Rar.txt.
Examples:
UnRAR.exe x -pPasswordOfArchive MyArchive.rar
UnRAR.exe x "-p!Password Of Archive!" MyArchive.rar
This switch with the password must be enclosed in double quotes if the password contains 1 or more spaces or other special characters according to the requirements for command line strings of the script interpreter (cmd.exe on Windows, bash or sh on Linux).
Only the first file of a multivolume archive must be specified on command line to extract all files and folders from all volumes (parts) of an archive.
Example:
UnRAR.exe x -pMyPassword MyMultiVolumeArchive.part1.rar
The other files (parts) of MyMultiVolumeArchive must be in same directory as first file and all parts must be present and valid.
The manual Rar.txt contains for command rv the paragraph:
RAR reconstructs missing and damaged volumes either when using rc command or automatically, if it cannot locate the next volume and finds the required number of .rev files when unpacking.
I tested the statement about automatically using *.rev files and it is not 100% true for v5.10 on Windows on extraction for multivolume RAR archives independent on which executable is used and if the multivolume RAR4 archive is password protected, completely encrypted or not protected. A missing part is automatically reconstructed using the recovery volumes, but not a damaged part resulting in one or more checksum errors on extraction of files. It is necessary to run a reconstruct on a multivolume RAR archive with a damaged volume before extraction can be done for all files and folders successfully.
The manual Rar.txt contains near top in chapter about RAR command line syntax the paragraph:
Many RAR commands, such as extraction, test or list, allow to use wildcards in archive name. If no extension is specified in archive mask, RAR assumes .rar, so * means all archives with .rar extension. If you need to process all archives without extension, use *. mask. *.* mask selects all files. Wildcards in archive name are not allowed when archiving and deleting.
So extraction of all files and folders from all password protected multivolume RAR archives in same directory is very easy:
UnRAR.exe x -idcdp -pCommonPassword *.rar
UnRAR automatically detects all *.rar files in the directory independent on type (single or multivolume archive) and decompresses them all whereby nothing is extracted twice. So after extraction of MyMultiVolumeArchive.part1.rar it continues automatically on part 2, 3, ... and after processing this multivolume archive, continues with next archive with a different file name in same directory.
It might be useful to use additionally the switch -ad to extract all files and folders of an archive to a folder with name of archive file to avoid extraction of files from different archives into same directory.
Example:
UnRAR.exe x -idcdp -ad -pCommonPassword *.rar
But take into account that the created folder contains also .part*1 in name for a multivolume archive. So using this switch on multivolume archives does not produce nice looking folder names.
On Windows the following command can be used to remove .part*1 from all folder names:
for /F "usebackq delims=" %D in ( `dir *part* /AD /B /ON` ) do ren "%D" "%~nD"
As batch file:
#echo off
for /F "usebackq delims=" %%D in ( `dir *part* /AD /B /ON` ) do ren "%%D" "%%~nD"
It is not possible to specify several RAR archives on a command line without usage of wildcards.
A command line like
UnRAR x -pArchivePassword FirstArchive.part1.rar SecondArchive.part001.rar ThirdArchive.rar
would be interpreted as order to extract the files SecondArchive.part001.rar and ThirdArchive.rar from multivolume archive FirstArchive.
Reconstruct several password protected multivolume archives
The command rc must be used instead of x to reconstruct a multivolume archive using recovery volumes (*.rev).
This command is not supported by UnRAR, only by Rar and WinRAR.
It is not possible to reconstruct all multivolume RAR archives in a directory with a single command. If a wildcard like *.rar is used with command rc, just the first RAR archive matching the file mask will be processed for checking archive integrity and reconstruct a volume if damaged or missing.
Therefore a command line respectively shell script (*.bat, *.sh) is required to run RAR with command rc on all multivolume archives in a directory.
But it is not necessary to first test archive integrity on each multivolume archive using command t as archives with no damaged or missing volume are not modified at all on reconstruct.
Example for a single archive:
Rar.exe rc -pArchivePassword MyMultiVolumeArchive.part001.rar
Here is a Windows batch file for that task:
#echo off
setlocal EnableDelayedExpansion
for /F "usebackq delims=" %%F in ( `dir *part*1.rar /A-D /B /ON` ) do (
rem Get string of archive file name after first dot which should be
rem the dot before part*1 as otherwise this procedure would produce
rem a wrong result. In other words this procedure does not work with
rem archive file names containing an additional dot before .part*.rar.
for /F "tokens=1,2 delims=." %%M in ( "%%~nF" ) do (
set PartNumber=%%N
rem Remove all zeros from "part*1"
set PartNumber=!PartNumber:0=!
rem Remove also "part" from "part*1".
set PartNumber=!PartNumber:part=!
rem Check if part number is 1 and not 11 or 101 or 111.
if "!PartNumber!" == "1" (
echo.
echo Reconstruct archive %%M
"C:\Program Files\WinRAR\Rar.exe" rc -idcd -pArchivePassword "%%F"
)
)
)
endlocal
Create a RAR archive for each subdirectory in a directory
WinRAR has after pressing button Add in toolbar the option Put each file to separate archive on tab Files explained in help opened by pressing button Help. WinRAR creates for each selected folder and selected file in root of the current directory a separate archive with name of folder / file.
But this is a feature supported by WinRAR only on using GUI. It is not supported on command line as far as I know whether by WinRAR nor by Rar.
Therefore it is necessary to run a small command line / shell script (*.bat, *.sh) to compress each folder in a directory into a separate archive. Just a single line is necessary to achieve that at least on Windows.
Windows command line:
for /F "usebackq delims=" %D in ( `dir /AD /B /ON` ) do "C:\Program Files\WinRAR\Rar.exe" a -cfg- -ep1 -inul -m5 -r -t -v10M "%D.rar" "%D"
Windows batch file:
#echo off
for /F "usebackq delims=" %%D in ( `dir /AD /B /ON` ) do "C:\Program Files\WinRAR\Rar.exe" a -cfg- -ep1 -inul -m5 -r-t -v10M "%%D.rar" "%%D"
The example compresses each folder recursively to an archive with same name using best compression, omitting the path to the folder in archive and creating a multivolume archive with 10 MB per volume. The created archives are additionally tested for integrity although this is usually not needed.

Batch file to rename extracted file if same name already exists

I work for a financial institution that pulls reports from out an outside source. I have an extremely basic batch file that checks folders for any zip file, extracts them to a different location, and moves the zip file to an "old" folder after extraction.
"C:\Program Files\WinZip\WZUNZIP.EXE" -d -o -sXXXXXXXXX C:\SFTP\ReportingAnalytics\Accounting\*.zip \\servername\Share2\Reporting_Analytics\Accounting\
MOVE C:\SFTP\ReportingAnalytics\Accounting\*.zip C:\SFTP\ReportingAnalyticsOld\Accounting
During the week, this works great. The problem is occurring on the weekends. These reports come over daily...unfortunately, with the same file name each day. So during the week, someone is working the report and there is no problem. On the weekends, no one works the report and they are getting overwritten (Friday's report comes in Saturday morning, gets overwritten on Sunday when Saturday's report comes in).
Is there an easy way to automatically rename these files upon extraction? ie AccountingReport1, AccountingReport2, and so on...
Any help would be greatly appreciated.
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir\one"
FOR %%a IN ("%sourcedir%\*.zip") DO (
ECHO("C:\Program Files\WinZip\WZUNZIP.EXE" -d -o -sXXXXXXXXX C:\SFTP\ReportingAnalytics\Accounting\%%a \\servername\Share2\Reporting_Analytics\Accounting\%%~na\
)
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
The required WZUNZIP commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO("...WZUNZIP to "...WZUNZIP to actually create the directories and extract the files.
You don't tell us how many files/directories are in the archive or indicate their names, and your use of -d -o implies there's a whole slough, hence this approach is to extract each .zip file to a new directory, nameofzip under \\servername\S...s\Accounting

Batch File to move files with the same string of characters into another folder with that string name

I am using Windows 7 Enterprise and have approximately 20 files per day for the last 365 days that I need to sort.
All of the files are in the same directory. Each file name also contains the date of the file's creation. The date is in the format MM-DD-YYY and starts at the 29th character of the file name. The files have the .csv extension.
I need to create a batch file to move all of the files with the same date into their own folder and onto another drive on my computer.
#echo off
setlocal EnableDelayedExpansion
for %%a in (*.csv) do (
set fileName=%%~a
set datePart=!fileName:~28,9!
if not exist "D:\!datePart!" md "D:\!datePart!"
move "%%a" "D:\!datePart!"
)
This script extracts the date part of each file name and uses it as the name of the folder to move the file to. If the folder doesn't exist, it is created, then the file is moved to it.
As written, the script iterates over the .csv files in the current directory. This is specified by the mask in the for loop: *.csv. You can change the mask to include a specific path to process, like C:\path\to\*.csv.
The target drive is also hard-coded and assumed to be D:. Change the corresponding entries of the script if you need to use a different drive.
Detail information on every command used in this script can be obtained by calling the command's built-in help from the command prompt, using either of the below syntaxes:
command /?
help command

how to find the last time stamp of the particular TYPE file in that directory?

how get the date and time of the last modified particular TYPE file in that directory
let me explain with an example
if i use the command dir *.reo /o:d
i get the all *.reo files in that directory sorted according to the date ..
this is the the last line of the output
29-03-2010 11.31 arun.reo
now i just want to copy the date and time of the last created file in variable or file .is it possible ?
You can do this using a batch file like this:
#echo off
setlocal enableextensions
for /f "delims=" %%f in ('dir *.reo /o:-d /b') do (
set dt=%%~tf
goto endloop
)
: endloop
echo %dt%
A little explanation:
dir *.reo /o:-d /b produces a list of all .reo files in the current directory, sorted by date in descending order (so that the last modified file comes first).
%%~tf expands to the date of the file specified by the %f variable.
It depends on what os your using. If you want just the last file
command one pipes the complete directory into a temp file
dir *.reo /o:d > temp.txt;
command two gets the last line of the temp file. Only works if you have the windowserver 2003 install which the link is provided below.
tail - 1 temp.txt;
Go to the Microsoft Windows Server 2003 download section at http://www.microsoft.com/windowsserver2003/
downloads/tools/default.mspx. Or, if that link does not work, visit http://www.microsoft.com/ and search for "Windows 2003". Once there, choose the "Downloads -> Tools" link.