Solved

BATCH SCRIPT HELP - Compress, Move, delete and increment

Posted on 2014-12-15
6
235 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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

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…
How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

744 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now