Monday 16 January 2017

 

=========================================================

cleanup_folderstructure.pl

=========================================================

#!/usr/bin/perl -w
# Cleanup_FolderStructure.pl
# This script takes a folder as input, recurses through the folder structure, and deletes any files it finds which are older than X days.
# It will also remove any empty folders which are left behind after the files are deleted.
# You can configure the script to either remove or ignore the first level of subfolders it finds using the $remove_top_level variable. (0=ignore, 1=remove)
# Version 1.2 - moves variables to input values

############ MODULES TO USE ###############
use File::Glob qw(bsd_glob);
use strict;

############ USER VARIABLES ###############


if (scalar @ARGV != 4)
{
    print "USAGE: $0 <Source Folder> <day limit> <Unique Name for Logs> <remove top level>\n";
    exit;
}

my $source_dir = $ARGV[0]; #"E:\\Shields"; # Set the source directory to start the listing from
my $log_path = "D:\\GIST\\LOGS";
my $max_days = $ARGV[1];
my $log_name = $ARGV[2];
my $remove_top_level = $ARGV[3];
my $info = "short";

############ GLOBAL VARS ##################
my $totalmoved = 0;
my $totaldups = 0;
my $totalskipped = 0;
my $totalnomatch = 0;
my ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings, $year);

sub GetTime
{
    ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime(time);
    $year = 1900 + $yearOffset;
    $month = $month + 1;
    if ($month < 10) { $month = "0" . "$month"};
    if ($dayOfMonth < 10) { $dayOfMonth = "0" . "$dayOfMonth"};
    if ($minute < 10) { $minute = "0" . "$minute"};
    if ($hour < 10) { $hour = "0" . "$hour"};
}

sub removeEmptyFolders
{
    my $source = $_[0];
    chdir($source) or die("Cannot access folder $source");
    my @directories;
   

    # Update the current Date and time
    GetTime();

    # Contstruct the Log filename
    my $logfile = $log_path . "\\cleanup-$log_name-" . $dayOfMonth . "-" . $month . "-" . $year . ".log";

    my $counter = 0;
    # Pass 1 - list the contents of the folder
    my @all_files = (bsd_glob("*"),bsd_glob(".*"));
    foreach (@all_files)
    {
        # check for the dodgy . and .. in the listed path (i.e. current dir and parent dir), as we don't want to recurse into these.
        # ... it's really not very fun when you start running this program outside of the given source path!
        open LOGFILE, ">>$logfile" or die "unable to open logfile $logfile for writing";
        if (($_ eq '.') || ($_ eq '..'))
        {
                #print "$_ matched . or .. and was discarded\n";
        }
        else   
        {
            # Check if the file is a directory or not. Directories don't get checked for mod time, but they get added to the directories array for
            # recursive processing to find files.
            if (-d $_)
            {
                #print "Adding new dir - $source\\$_\n";
                push @directories, "$source\\$_";
                $counter++;
            }
            else
            {
                # If it's not a dir then it's a file. Find the mod time of the file, and delete that file if it's old.
                my $days_old = -M $_;
                if ((-f $_) && ($days_old > $max_days))# check if the file is an actual file and that it's more than 2 days old
                {
                    print LOGFILE "Cleanup: Deleting $_ ($days_old days old)\n";
                    #$counter++;
                    unlink ("$_");
                }
                else
                {
                    # If it's a file but not older than our limit then add to the counter to say files were found
                    print LOGFILE "Cleanup: Ignoring $_ ($days_old days old)\n";
                    $counter++;
                }
            }
        }
        close LOGFILE;
    }
   
    if ($counter == 0)
    {
            # this means that no subfolders or files were found, so we should be able to delete the folder
            print "==> CLEANUP - Delete $source\n";   
            return 1;
    }
    else
    {
        foreach (@directories) # recursively call itself to process any directories which have been found
        {
            my $return_value = &removeEmptyFolders($_);
            chdir "$source" or die "cannot chdir to $source: $!";
            if ($return_value == 1)
            {
                    # If it returns 1 then delete the folder
                    print "==> CLEANUP - Deleting $_\n";
                    rmdir ("$_") or print "$!\n";
                    open LOGFILE, ">>$logfile" or die "unable to open logfile $logfile for writing";
                    print LOGFILE "==> CLEANUP - Deleting $_\n";
                    close LOGFILE;       
            }
        }
       
        my @second_pass = (bsd_glob("*"),bsd_glob(".*"));
        my $secondcounter = 0;
        foreach (@second_pass)
        {
            if (($_ eq '.') || ($_ eq '..'))
            {
                    #print "$_ matched . or .. and was discarded\n";
            }
            else
            {
                    $secondcounter++;
            }
        }
       
        if ($secondcounter == 0)
        {
                # this means that no subfolders or files were found, so we should be able to delete the folder
                print "==> CLEANUP (Pass 2) - Delete $source\n";
                return 1;
        }
        else
        {
                return 0;
        }
    }
}

############ DRIVER FUNCTION ##############
# Check that the log path exists
if (!-d $log_path)
{
    print "Log Path - $log_path does not exist - please create it to run this script.\n";
    exit;
}

if (!-d $source_dir)
{
    print "Source Dir - $source_dir does not exist - please create it to run this script.\n";
    exit;
}
else
{
    print "Analyzing $source_dir\n";
}
my $waiting = 0;

chdir($source_dir) or die("Cannot access folder $source_dir");
GetTime();

my $logfile = $log_path . "\\cleanup-$log_name-" . $dayOfMonth . "-" . $month . "-" . $year . ".log";
my @directories;
my @all_files = (bsd_glob("*"),bsd_glob(".*"));

foreach (@all_files)
{
    if (($_ eq '.') || ($_ eq '..'))
    {
            #print "$_ matched . or .. and was discarded\n";
    }
    else
    {
        if (-d $_)
        {
            my $current_folder = "$source_dir\\$_";
            GetTime();
           
            open LOGFILE, ">>$logfile" or die "unable to open logfile $logfile for writing\n";
            print LOGFILE "[$dayOfMonth/$month/$year $hour:$minute] Found $source_dir\\$_ \n";
            push @directories, "$source_dir\\$_";
            close LOGFILE;
        }
    # If it's not a dir then it's a file. Find the mod time of the file, and delete that file if it's old.
    my $days_old = -M $_;
    if ((-f $_) && ($days_old > $max_days))# check if the file is an actual file and that it's more than 2 days old
    {
        open LOGFILE, ">>$logfile" or die "unable to open logfile $logfile for writing\n";
        print LOGFILE "Cleanup: Deleting $_ ($days_old days old)\n";
        unlink ("$_");
    }
    else
    {
        # If it's a file but not older than our limit then add to the counter to say files were found
        open LOGFILE, ">>$logfile" or die "unable to open logfile $logfile for writing\n";
        print LOGFILE "Cleanup: Ignoring $_ ($days_old days old)\n";
        close LOGFILE;
    }
    }
}

chdir ($source_dir);
if (scalar(@directories) > 0)
{    
    foreach (@directories)
    {
        GetTime();
        open LOGFILE, ">>$logfile" or die "unable to open logfile $logfile for writing";
        print "**** [$dayOfMonth/$month/$year $hour:$minute] Starting to process $_ ****\n";
        print LOGFILE "**** [$dayOfMonth/$month/$year $hour:$minute] Starting to process $_ ****\n";
        close LOGFILE;       
       
        # if the return value here is 1 from the function then usually we delete the folder, but we don't want to remove the top level folders in this case
        my $return_value = &removeEmptyFolders($_);
       
        if ($remove_top_level)
        {
            # Remove the top level folder if it has been requested!
            if ($return_value == 1)
            {
                chdir ($source_dir);
                # If it returns 1 then delete the folder
                print "==> CLEANUP - Deleting $_\n";
                rmdir ("$_") or print "$!\n";
                open LOGFILE, ">>$logfile" or die "unable to open logfile $logfile for writing";
                print LOGFILE "==> CLEANUP - Deleting $_\n";
                close LOGFILE;
            }
            else
            {
                open LOGFILE, ">>$logfile" or die "unable to open logfile $logfile for writing";
                print LOGFILE "==> CLEANUP - Ignoring Top Level Folder: $_\n";
                close LOGFILE;
            }
        }
        print "Completed deletion of files older than $max_days from $_\n";       
    }
}   

=========================================================

cleanup file structure.bat

=========================================================

@ echo off
Q:
cd Q:\ShieldsFiles\Shields

echo [%DATE%] [%TIME%] Start.

forfiles.exe /p Q:\ShieldsFiles\Shields\Outgoing /s /m *.* /d -10 /c "cmd /c del @file"
forfiles.exe /p Q:\ShieldsFiles\Shields\BASH /s /m *.* /d -21 /c "cmd /c del @file"
forfiles.exe /p Q:\ShieldsFiles\Shields\BASHDupsZip /s /m *.* /d -21 /c "cmd /c del @file"
forfiles.exe /p Q:\ShieldsFiles\Shields\BASHDups /s /m *.* /d -21 /c "cmd /c del @file"
forfiles.exe /p Q:\ShieldsFiles\Shields\BASHRescan /s /m *.* /d -21 /c "cmd /c del @file"
 
echo [%DATE%] [%TIME%] Done.

 

=========================================================

deleteanythingunderthat folder.bat

=========================================================

@ echo off
c:
cd C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp
FOR /D %%p IN ("C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\*.*") DO rmdir "%%p" /s /q
forfiles.exe /p C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp /s /m *.* /d -1 /c "cmd /c del @file"
mkdir c:\temp\new
move C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\*.* c:\temp\new
rmdir /s /q c:\temp\new

 

=========================================================

deloldestfile..cmd

=========================================================

@echo off
setlocal
set Folder=E:\W\Screenshots
set FileMask=*.png
set OldestFile=
for /f "delims=" %%a in ('dir /b /o:d "%Folder%\%FileMask%" 2^>NUL') do (
    set OldestFile=%%a
    goto Break
)
:Break
if "%OldestFile%"=="" (
    echo No files found in '%Folder%' matching '%FileMask%'!
) else (
    del "%Folder%\%OldestFile%"
)

0 comments:

Post a Comment

ShortNewsWeb

Blog Archive

Recent Comments

Popular Posts

Translate

System Admin Share

Popular

Total Pageviews