Thursday 22 October 2009

Autorotate and renaming the files as for date with batch script and vbscript (logrotate)

It explained to write the script for rotate the log files and delete files older 30 days. these scripts taken from other people sites and modified for this convenience.
For this script you need FDATE program to mention the date format to insert in to the file name.
and here used the VB script to compare dates, creation and today date and deleting. So many people written the batch script for this with environment variables in DOS. I thought that script is very long and little bit confusing.

Here is the batch script for rename the log files


@echo off
Rem the below line come in to the "c:\>" this file kept in C drive
cd\
rem stoping the rsync service
Net stop rsyncd


for /f "tokens=1,2 delims=/\-." %%f in ('FDATE /Ff /Occyymmdd') do REN c:\rsync\rsyncd.log %%f%%g.log
gzip -9 c:\rsync\*.*

c:\temp\test.vbs



Net start rsyncd

pause

Wednesday 14 October 2009

Autorotate and renaming the files as for date with Power shell (logrotate)

Hi all, I am not good in scripting. My manager asked me to write the script on windows server to rename the log files as the date and compress them with gzip and delete the files 30 days old from server. The below script in power shell
#logrotate script
#

$k = get-childitem #Here you can mention the directory path which one the files contain

foreach ($m in $k) #mentioning the value for each item in the directory with 'k'
{
$n = (get-date -uformat "%d%m%y") #selecting the format of the date to add to the file name
$newname = "$n.log" #making the new name format
rename-item $m $newname #making rename here
}

gzip -9 # here gzip the file

$a = get-childitem #here we starting the date comparison for creation date and today date
foreach ($x in $a)
{$y = ((get-date) - $x.CreationTime) # date difference is here
if ($y -gt 30 -and $x.PSISContainer -ne $True) # here we checking whether is it file or Directory

{$x.Delete() # deleting old file here from directory
}
}

The above script can change for your flexibility, for moving the files from one directory to other and stop the services before before you rename and other things.
you can do the services like rsync start and stop.
here is the one example for those things. The below one stop the rsync service and rename the log files of rsync and gzip the file and delete the older than 30 days.

#logrotate script
#
Net stop rsyncd

$k = get-childitem c:\temp\r*.log
foreach ($m in $k)
{
$n = (get-date -uformat "%d%m%y")
$newname = "$n.log"
rename-item $m $newname
}

gzip -9 c:\cygwin\var\log\r*.log

$a = get-childitem c:\temp\*.gz
foreach ($x in $a)
{$y = ((get-date) - $x.CreationTime).days
if ($y -gt 30 -and $x.PSISContainer -ne $True)

{$x.Delete()
}
}
Net start rsyncd