Delete files older than…. in Powershell

delete_key_eraser_inhandRecently I’ve found myself in a situation where I had to periodically delete files older than 7 days. I could have done it manually, but being busy, I often forgot to do it. The script I’m about to show you is a bit modified than the original, but, the principle is the same. Here I’ve added a posibilty to manually enter the directory name. In your script, you can define it, so it is being run automatically, without your intervention.

Here’s the code :

Function GetOldFile
{
param ($Dir = $(Read-host "Unesi putanju do direktorija")),
($Days = $(Read-Host "Brišem fileove starije od koliko dana?"))
$TargetFolder = $Dir
if (Test-Path $TargetFolder)

{
Write-host "DIREKTORIJ JE :" $TargetFolder -foregroundcolor "Red"
#Write-Host `a `a `a `a `a - odkomentirati ako zelimo da pc speaker vristi :)
Write-Host "UPS, krivi folder! Stisni 'Ctrl + C' za prekid - imas 5 sekundi za prekid" -foregroundcolor "Yellow"
Start-sleep -s 5
$Now = Get-Date
$LastWrite = $Now.AddDays(-$days)
$Files = get-childitem $TargetFolder -include *.log -recurse |Where {$_.LastWriteTime -le "$LastWrite"}
foreach ($File in $Files)
{write-host "Brišem file $File" -foregroundcolor "Red"; Remove-Item $File | out-null}
}
Else
{Write-Host "Direktorij $TargetFolder ne postoji! Provjeri path!"}
}
GetOldFile

The questions in the script are in Croatian, but anyone with a little bit of programming experience will be able to change it, because the script is pretty straight forward. But, if you’re lazy as most of us are, here is the translated script :)

Function GetOldFile
{
param ($Dir = $(Read-host "Enter destination folder path")),
($Days = $(Read-Host "Delete files older than how many days ?"))
$TargetFolder = $Dir
if (Test-Path $TargetFolder)
{
Write-host "Target folder path is :" $TargetFolder -foregroundcolor "Red"
#Write-Host `a `a `a `a `a - uncomment if you would like to hear the pc speaker #warning :)
Write-Host "WRONG FOLDER! Press 'Ctrl + C' to abort"-foregroundcolor "Yellow"
Start-sleep -s 5
$Now = Get-Date
$LastWrite = $Now.AddDays(-$days)
$Files = get-childitem $TargetFolder -include *.log -recurse |Where {$_.LastWriteTime -le "$LastWrite"}
foreach ($File in $Files)
{write-host "Deleting file $File" -foregroundcolor "Red"; Remove-Item $File | out-null}
}
Else
{Write-Host "Folder $TargetFolder doesnt exist! Recheck the folder path!"}
}
GetOldFile

Be careful with this script, because it will delete all the files in the subfolder also! Notice the “-recurse” in the script..

Now, to make your life even easier, you can add this script to scheduled tasks and set it to run whenever you need it.

First thing that we need to do is to set the folder path as a constant value. Instead of

param ($Dir = $(Read-host "Enter destination folder path")),
($Days = $(Read-Host "Delete files older than how many days ?"))

we need to define $Dir and %Days in the script. That is done like this:

$Days = "2"
$TargetFolder = "C:\pathtofolder"

So the script looks like this:

Function GetOldFile
{
$Days = "2"
$TargetFolder = "
C:\pathtofolder"
if (Test-Path $TargetFolder)
{
$Now = Get-Date
$LastWrite = $Now.AddDays(-$days)
$Files = get-childitem $TargetFolder -include *.log -recurse |Where {$_.LastWriteTime -le "$LastWrite"}
foreach ($File in $Files)
{write-host "Deleting file $File" -foregroundcolor "Red"; Remove-Item $File | out-null}
}
Else
{Write-Host "Folder $TargetFolder doesnt exist! Recheck the folder path!"}
}
GetOldFile

Notice that I have removed couple of lines from that script that are not neccesary to the script to function properly. If you like, you can also remove the line where the script writes out the names of the files that are being deleted.

Second thing you need to do is make sure that Powershell is set to execute Powershell scripts, instead of only allowing interactive commands to be run in the Powershell environment.

Type the following at the Powershell command prompt:

set-executionpolicy RemoteSigned

After that, create a .bat file and name it whatever you like ( i.e dltfilesolderthanXYday.bat) and paste the following entry in:

powershell -command "& 'SCRIPTNAME.ps1' "

All that is left to do is to create a Scheduled Task in Windows. Add a task that will run the .bat file every number of days you need.

Enjoy!

5 comments

  1. Thanks, really helpful. The script only complained when there were no files matching the criteria. Substitution of the get-childitem cmdlet directly into foreach helped:

    foreach ($File in get-childitem $TargetFolder -include *.log -recurse |Where {$_.LastWriteTime -le “$LastWrite”}) { … }

  2. Nice but how can i write out-file I wana save the log to a txt file but dosent work with this method

    {write-host “Deleting file $File” -foregroundcolor “Red”; Remove-Item $File | out-file “c:\log.txt” }

    can anyone help me

  3. Hi can anyone help me with the out-file this script is realy cool but i need to save logs about his work so i want the output to save in to a txt file but i can’t.
    I tried this way:
    {write-host “Deleting file $File” -foregroundcolor “Red”; Remove-Item $File | out-file “C:\log\11.txt”}
    }

    But it dosen’t work any sugestions

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>