DEV Community

Roel
Roel

Posted on

🚀 Quick Guide: Delete Old Files Using PowerShell

Hey there! Need to regularly clean up old files in a directory? Here's a quick guide using a PowerShell script.

🛠️ The Script (delete_old_files.ps1):

param (
    [string]$path
)

$ThirtyDaysAgo = (Get-Date).AddDays(-30)
$logFileName = "log_delete_"+(Get-Date -Format "yyyyMMddHHmmss") + ".txt"
$logPath = Join-Path $PSScriptRoot $logFileName

function WriteToLog($message) {
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    Add-Content -Path $logPath -Value "[$timestamp] $message"
}

Get-ChildItem -Path $path -Recurse -File | Where-Object { $_.LastWriteTime -lt $ThirtyDaysAgo } | ForEach-Object {
    try {
        Remove-Item $_.FullName -Force
        $msg = "Deleted $($_.FullName)"
        Write-Output $msg
        WriteToLog $msg
    } catch {
        $errMsg = "Failed to delete $($_.FullName): $_"
        Write-Error $errMsg
        WriteToLog $errMsg
    }
}

Enter fullscreen mode Exit fullscreen mode

This script also writes a log file so that you never have to worry about what it might or might not delete.

🚀 How to Run:

  1. Save the script to delete_old_files.ps1.
  2. Open PowerShell (Run as Admin for best results).
  3. Navigate to the script's directory.
  4. Run:
.\delete_old_files.ps1 -path "C:\path\to\your\directory"
Enter fullscreen mode Exit fullscreen mode

📅 Schedule it with Windows Task Scheduler:

  1. Open Task Scheduler.
  2. Create a new basic task.
  3. Set it to run daily or as you wish.
  4. Action: Start a program > powershell.
  5. Arguments:
-ExecutionPolicy Bypass -File "C:\path\to\delete_old_files.ps1" -path "C:\your\target\directory"
Enter fullscreen mode Exit fullscreen mode

Done! 🎉 Your directory will now stay clean from files older than 30 days.

Remember: Always backup important files before running deletion scripts. Happy coding! 🚀

Top comments (0)