PowerShell: automatically delete files older than X days

In this tutorial, we will see how to delete files older than X day using PowerShell.

This type of script is often used in businesses on servers to rotate logs.

If we take the example of IIS, the logs are never deleted, which means that after 3 years, we end up with more than 1,000 files for a site.

To start, we will need two variables:

  • $LogsPath : which will define the location where you want to delete the logs
  • $MaxDayToKeep : which will indicate the number of days we wish to keep

We will start with the variable by $LogPath.

$LogPath = "C:\inetpub\logs"

For this variable, nothing complicated, just indicate the path where the files are located.

For the $MaxDayToKeep variable, it will depend on the solution you are going to select to recover the files, in this tutorial, we will see 2 and depending on the solution $MaxDayToKeep take a positive or negative value.

$MaxDayToKeep = -5
$MaxDayToKeep = 5

With the variables declared, we will now move on to the first step of the script, which retrieves the files that we wish to delete. For this step, there are a multitude of ways to do this, here are two:

Method 1 with a negative value for $MaxDayToKeep:

$FilesToDelete = dir $LogPath -Recurse -File *.log | Where LastWriteTime -lt ((get-date).AddDays($MaxDayToKeep))

Method 2 with a positive value but which can be done in 2 instructions:

$LastWrite = $Now.AddDays(-$MaxDayToKeep )
$FilesToDelete = Get-ChildItem $LogPath -Recurse | Where-Object { $_.Name -like "*.log" } | Where-Object { $_.lastWriteTime -le "$lastwrite" } | Select-Object FullName

The second step will be to browse the files retrieved in the $FilesToDelete variable and delete them.

if ($FilesToDelete .Count -gt 0){ 
      ForEach ($item in $FilesToDelete ){ 
            Remove-Item $item.FullName -Verbose

We now have all the elements to create a script.

Méthod 1 :

Méthod 2 :

You now know how to set up log rotation on Windows with PowerShell.

Leave a Comment