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







No comments:

Post a Comment