Windows admin PowerShell

Find and delete files older than N days

Delete files older than a number of days from a folder, with -WhatIf support and a guard against drive roots and system folders.

LanguagePowerShell
What it does to the systemMakes changes. Test it on one computer first.

Log and temp folders grow until the drive is full. A cleanup one-liner is easy to write and easy to point at the wrong folder.

This script deletes files older than a number of days. It supports -WhatIf, and it refuses to run on a drive root or a system folder.

PowerShell
<#
  Delete files older than N days from a folder.
  Always run it with -WhatIf first. Needs rights to delete in the folder.
  Example: .\Remove-OldFile.ps1 -Path D:\Logs -Days 30 -Filter *.log -Recurse -WhatIf
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param(
    [Parameter(Mandatory = $true)]
    [string]$Path,

    # Files last changed more than this many days ago are deleted.
    [ValidateRange(1, 36500)]
    [int]$Days = 30,

    # Which files, for example *.log
    [string]$Filter = '*',

    # Also clean the folders below the path.
    [switch]$Recurse
)

$root = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath.TrimEnd('\')

# Guard: never run on a drive root or a system folder.
$blocked = @($env:windir, $env:ProgramFiles, ${env:ProgramFiles(x86)}, $env:ProgramData, "$env:SystemDrive\Users")
if ($root.Length -le 2 -or $blocked -contains $root) {
    throw "Refusing to clean '$root'. Choose a folder below it."
}

$cutoff = (Get-Date).AddDays(-$Days)
$files = @(Get-ChildItem -LiteralPath $root -Filter $Filter -File -Recurse:$Recurse -ErrorAction SilentlyContinue |
    Where-Object { $_.LastWriteTime -lt $cutoff })

$deleted = 0
$bytes = 0
foreach ($file in $files) {
    if ($PSCmdlet.ShouldProcess($file.FullName, 'Delete file')) {
        try {
            Remove-Item -LiteralPath $file.FullName -Force -ErrorAction Stop
            $deleted++
            $bytes += $file.Length
        }
        catch {
            Write-Warning "Not deleted: $($file.FullName) - $($_.Exception.Message)"
        }
    }
}

[pscustomobject]@{
    Folder       = $root
    OlderThan    = $cutoff
    FilesFound   = $files.Count
    FilesDeleted = $deleted
    FreedMB      = [math]::Round($bytes / 1MB, 1)
}

How to use it

  1. Save the script as Remove-OldFile.ps1.
  2. Run .\Remove-OldFile.ps1 -Path D:\Logs -Days 30 -Filter *.log -WhatIf. It lists each file and deletes nothing.
  3. Check the list. Change -Days or -Filter until it is right.
  4. Run the same command without -WhatIf to delete the files.
  5. Add -Recurse only when you also want the folders below the path cleaned.

Good to know

  • The script uses the last write time. It deletes files only, so empty folders stay.
  • Deleted files do not go to the Recycle Bin. Keep a backup if you may need them.
  • Files that are in use give a warning and stay in place.
delete old files cleanup log files WhatIf LastWriteTime
✉

Get new articles in your inbox

SCCM guides, AI tools, automation tips — sent when published. No spam.