Tag Archives: script

Delete files and folders older than…

Here is a little PowerShell script  that will delete all files and folders (and all the subdirectories and files) that have the created and last modified times older than $olderthan days. You just need to change the following:

$path – specify the path where the script will search.
$olderthan – number of days you want the files and folders to be kept on the server.

You can change the days in hours, minutes,months and even years. All you have to do is change “adddays” with what you need. Example: “addminutes”,”addyears”, etc.

#Delete files older then specified days
#Version 0.1
#Created by nraddan@yahoo.com

$path="F:\Shared"
$olderthan=14
$olderdate = (get-date).adddays(-$olderthan)
$FilteredList = Get-ChildItem $path -force -recurse | where { ($_.lastwritetime -le $olderdate) -and ($_.creationtime -le 

$olderdate) }

if ($FilteredList.count -ne 0) {
#remove files older then $olderthan days
    $FilteredList | where { $_.Length -ne $null } | % {
        $creation=(get-date) - $_.creationtime
        $modified=(get-date) - $_.lastwritetime
        write-host Deleting file $_.PSPath ! "( $creation - $modified )"
        remove-item $_.PSPath -Force
        }
#remove folders older then $olderthan days
    $FilteredList | where { $_.Length -eq $null } | % {
        $creation=(get-date) - $_.creationtime
        $modified=(get-date) - $_.lastwritetime
        write-host Deleting file $_.PSPath ! "( $creation - $modified )"
        remove-item $_.PSPath -Force
        }
}

The script was test on Windows 2008 R2 Standard.

Email alert for low disk space

This is a little bash script that will send an email to your specified address when the disk space on a partition is bellow a certain value.

#!/bin/bash
percent_limit=95
partition="/partition"
email="email@example.com"
subject="whatever you wanna write"

disk_p=`/bin/df -h / | /bin/grep $partition | /usr/bin/awk '{ print $5; }' | /bin/sed -e 's/%//'`
disk_v=`/bin/df -h / | /bin/grep $partition | /usr/bin/awk '{ print $4; }'`

if [ $disk_p -gt $percent_limit ]; then
#  /bin/echo "Disk space is $disk_p% - $disk_v free! "
  /bin/echo "$subject" | /usr/bin/mail $email -s "Disk space is $disk_p% - $disk_v free! "
fi

You just have to change the first 4 lines to your needs. Save the bash script and do a

chmod +x /path/to/script

Now we just have to make it run every X hours. For that just add the following line in the cron (crontab -e) :

# low disk warning
01  */X *  *  *  /path/to/script.sh  1>/dev/null 2>/dev/null

Exit from the crontab editor with ctrl+x and wait for the script to do it’s magic.

Hope this helped, it sure helped me.