Solved

BATCH SCRIPT HELP - Compress, Move, delete and increment

Posted on 2014-12-15
6
249 Views
Last Modified: 2014-12-16
HI All,

I have the following BAT script:

@echo off

REM Define file and folder locations
set BaseDir=c:\TestFiles
set DestZip=c:\OldLogs\output.zip
set z=c:\program files\7-zip\7z.exe

REM Zip all files and folders
"%z%" a -tzip "%DestZip%" -r "%BaseDir%\*.*"

Open in new window



This script grabs the contents of C:\TestFiles, compresses all the files and stores it in c:\OldLogs\output.zip. This is perfect, although i need the script to now:

1) Delete the old files from C:\TestFile where older than x days
2) The output.zip needs to increment each time the script is run, a time stamp would be ideal here:

20141215_1239
-20141216_1239

and so on...

Many thanks,
0
Comment
Question by:Richiep86
  • 3
  • 2
6 Comments
 
LVL 83

Expert Comment

by:oBdA
ID: 40500256
Try this; the script is currently in test mode and will only display the "del" and "7z" commands it would normally run; remove the two uppercase ECHOs in lines 21 and 25 to run it for real.
@echo off
setlocal enabledelayedexpansion

REM Define file and folder locations
set BaseDir=c:\TestFiles
set DestZip=c:\OldLogs\output.zip
set SevenZip=%ProgramFiles%\7-zip\7z.exe
set DeleteOlder=365

REM Zip all files and folders
echo Getting time ...
for /f "tokens=1-9" %%a in ('wmic.exe Path Win32_LocalTime Get Day^,DayOfWeek^,Hour^,Minute^,Month^,Quarter^,Second^,WeekInMonth^,Year ^| find /v ""') do (
	set /a Line += 1
	if "!Line!"=="1" (set VarA=%%a&set VarB=%%b&set VarC=%%c&set VarD=%%d&set VarE=%%e&set VarF=%%f&set VarG=%%g&set VarH=%%h&set VarI=%%i)
	if "!Line!"=="2" (set !VarA!=%%a&set !VarB!=%%b&set !VarC!=%%c&set !VarD!=%%d&set !VarE!=%%e&set !VarF!=%%f&set !VarG!=%%g&set !VarH!=%%h&set !VarI!=%%i)
)
for %%a in (Month Day Hour Minute Second) do (if !%%a! LSS 10 set %%a=0!%%a!)
set TimeStamp=%Year%%Month%%Day%_%Hour%%Minute%%Second%

echo Deleting old files ...
forfiles.exe /p "%BaseDir%" /m * /s /d -%DeleteOlder% /c "cmd.exe /c if @isdir==FALSE (ECHO del /f @path)"

echo Compressing '%BaseDir%' ...
for %%a in ("%DestZip%") do (set DestZip=%%~dpna-%TimeStamp%%%~xa)
ECHO "%SevenZip%" a -tzip "%DestZip%" -r "%BaseDir%\*.*"

Open in new window

0
 
LVL 35

Expert Comment

by:Kimputer
ID: 40500286
For ease, I usually use VBscript. This should work (though try to figure out the date string by using echo, as it depends on the system regional settings):

Dim fso, startFolder, OlderThanDate, objShell, strCommand, BaseDir, DestZip, zipexe
 
Set fso = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("WScript.Shell")

BaseDir = "=c:\TestFiles\" ' folder for source data
DestZip = "c:\OldLogs\" & right(left(Date,8),2)  & right(left(Date,5),2) & left(Date,2) & "-" & left(Time,2) & right(left(Time,5),2) & right(left(Time,8),2) & ".zip"
OlderThanDate = DateAdd("d", -3, Now)
zipexe = "c:\program files\7-zip\7z.exe"



"%z%" a -tzip "%DestZip%" -r "%BaseDir%\*.*"
strCommand = """" & zipexe & """  a -tzip " &  DestZip " """ & BaseDir & "*.*"""
objShell.Run strCommand, 1, True


DeleteOldFiles BaseDir, OlderThanDate
 
Function DeleteOldFiles(folderName, BeforeDate)
   Dim folder, file, fileCollection, folderCollection, subFolder
 
   Set folder = fso.GetFolder(folderName)
   Set fileCollection = folder.Files
   For Each file In fileCollection
      If file.DateLastModified < BeforeDate Then
           fso.DeleteFile file
      End If
   Next

End Function

Open in new window

0
 

Author Comment

by:Richiep86
ID: 40500442
ODBA - Excellent. Thank you, although a slight amendment if i may?

I only want to ZIP AND DELETE the logs which are OVER 30 days old. If they are NOT older than 30 days, can we ignore them?

Thanks for you prompt and professional answer :)

RIch
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 83

Expert Comment

by:oBdA
ID: 40500682
Sorry, then you need to be a more specific.
In the initial question, you wrote:
1) Delete the old files from C:\TestFile where older than x days
2) The output.zip needs to increment each time the script is run, a time stamp would be ideal here
Now you write:
I only want to ZIP AND DELETE the logs which are OVER 30 days old. If they are NOT older than 30 days, can we ignore them?
Just to make sure I understood you correctly: Basically, you want to move only files older than a certain age to an archive, while keeping the more recent files in the same location?
0
 
LVL 83

Accepted Solution

by:
oBdA earned 500 total points
ID: 40501230
Here's a version that first moves all files older than x days to a temporary folder, zips the temporary folder, and removes the temporary folder.
As before, it's in test mode (which will list all files it would move); remove the uppercase ECHOs in lines 34 and 41, and the uppercase /L in the robocopy command,, line 22.
@echo off
setlocal enabledelayedexpansion

REM Define file and folder locations
set BaseDir=C:\TestFiles
set ZipDir=C:\DeleteMe
set DestZip=c:\OldLogs\output.zip
set SevenZip=%ProgramFiles%\7-zip\7z.exe
set DeleteOlder=365

REM Zip all files and folders
echo Getting time ...
for /f "tokens=1-9" %%a in ('wmic Path Win32_LocalTime Get Day^,DayOfWeek^,Hour^,Minute^,Month^,Quarter^,Second^,WeekInMonth^,Year ^| find /v ""') do (
	set /a Line += 1
	if "!Line!"=="1" (set VarA=%%a&set VarB=%%b&set VarC=%%c&set VarD=%%d&set VarE=%%e&set VarF=%%f&set VarG=%%g&set VarH=%%h&set VarI=%%i)
	if "!Line!"=="2" (set !VarA!=%%a&set !VarB!=%%b&set !VarC!=%%c&set !VarD!=%%d&set !VarE!=%%e&set !VarF!=%%f&set !VarG!=%%g&set !VarH!=%%h&set !VarI!=%%i)
)
for %%a in (Month Day Hour Minute Second) do (if !%%a! LSS 10 set %%a=0!%%a!)
set TimeStamp=%Year%%Month%%Day%_%Hour%%Minute%%Second%

echo Moving old files ...
robocopy.exe "%BaseDir%" "%ZipDir%" /e /mov /r:0 /minage:%DeleteOlder% /ts /L
if errorlevel 4 (
	echo Error when moving the files to the target folder.
	exit /b 1
)
if not errorlevel 0 (
	echo No files to archive found.
	goto :eof
)

echo Compressing '%ZipDir%' ...
for %%a in ("%DestZip%") do (set DestZip=%%~dpna-%TimeStamp%%%~xa)
ECHO "%SevenZip%" a -tzip "%DestZip%" -r "%ZipDir%\*.*"
if errorlevel 1 (
	echo Error when zipping the old folder.
	exit /b 1
)

echo Removing  '%ZipDir%' ...
ECHO rd /s /q "%ZipDir%"

Open in new window

0
 

Author Closing Comment

by:Richiep86
ID: 40502370
Thank you for your excellent advise and speedy responses,
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I have published numerous articles here at Experts Exchange that present programs/scripts written in a language called AutoHotkey. Each of those articles has a brief paragraph describing where to download the product and how to install it. I have al…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

785 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question