Winscripter
  WSH
  Forums
  Downloads
  Books
  Links
  Amazon




Login
Register

© winscripter.com
1998-2004







Script: File Rotator

Posted by on Tuesday, January 18, 2005 (PST)

Script: Rotate files where the most current file has the lowest number in the archive. When files exceed the retention period, they are deleted. Typically used for log files, backups, etc..

The script operates as follows.  Assume that we have a logfile called, "mylog.txt".  I want to keep the last five copies as well as the current logfile.  The files will be rotated with the following convention:


mylog.txt -> mylog1.txt
mylog1.txt -> mylog2.txt
mylog2.txt -> mylog3.txt
mylog3.txt -> mylog4.txt
mylog4.txt -> mylog5.txt
mylog5.txt -> <delete>
 

I have included a couple of function to provide a working sample, main, print, MakeFile.  The functions that are needed are Archive and GetFileName.


var fso = new ActiveXObject( "Scripting.FileSystemObject" );
// Function to demo archiving
function main()
{
 for( k = 0; k < 10; k++ )
 {
  print( "Current Loop: " + k );
  Archive( "mytest.txt", 5 );
  MakeFile( "mytest.txt" );
  
  WScript.Sleep( 1000 * 31 );
 }
}
main();

// Archive - handles file rotation
function Archive( srcfile, retention )
{
 // Find the next open ID for file rename
 var NextID = 0;
 for( i = 1; i <= retention; i++ )
 {
  var fname = GetFileName( srcfile, i );
  if( !fso.FileExists( fname ) )
  {
   NextID = i;
   break;
  }
 }
 // If we did not detect a "free" ID to use, we are at max.
 if( NextID == 0 )
  NextID = retention;
  
 // Begin Renaming Loop
 for( j = NextID; j > 0; j-- )
 {
  var tempSrc;
  var tempDst;
  if( j == 1 )
  {
   tempSrc = srcfile;   
   tempDst = GetFileName( srcfile, 1 );
  }
  else
  {
   tempSrc = GetFileName( srcfile, j - 1 );
   tempDst = GetFileName( srcfile, j );
  }
  fso.CopyFile( tempSrc, tempDst, true );
 }
}

// Returns new file name for archive
function GetFileName( srcfile, id )
{
 var fname = String( srcfile );
 return( fname.replace( /(\.)/gi, id + "." ) );
}
// Create a dummy file for testing purposes
function MakeFile( fname )
{
 var f = fso.OpenTextFile( fname, 2, true );
 var msg = "This is a test file: " + new Date().toTimeString();
 f.WriteLine( msg );
 f.Close();
}
// Print Wrapper
function print( msg )
{
 WScript.Echo( msg );




WSH and ADSI Administrative Scripting


Winscripter   |  WSH   |  Forums   |  Downloads   |  Books   |  Links   |  Amazon