0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Delete Old Files Easily

Use Get-ChildItem -Path 'folder_path' -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-days) } | Remove-Item to delete files older than a set number of days in PowerShell.
📋

Examples

InputDelete files older than 30 days in C:\Temp
OutputFiles in C:\Temp last modified more than 30 days ago are deleted.
InputDelete files older than 7 days in D:\Logs
OutputFiles in D:\Logs last modified more than 7 days ago are deleted.
InputDelete files older than 0 days in C:\Test
OutputAll files in C:\Test older than today (i.e., all files modified before now) are deleted.
🧠

How to Think About It

To delete old files, first find all files in the target folder. Then check each file's last modified date. If the file is older than the specified number of days, delete it. This ensures only files older than the threshold are removed.
📐

Algorithm

1
Get the folder path and number of days as input.
2
List all files in the folder.
3
For each file, check if its last modified date is older than current date minus the number of days.
4
If yes, delete the file.
5
Report completion.
💻

Code

powershell
param(
    [string]$FolderPath = "C:\Temp",
    [int]$DaysOld = 30
)

$CutoffDate = (Get-Date).AddDays(-$DaysOld)
Get-ChildItem -Path $FolderPath -File | Where-Object { $_.LastWriteTime -lt $CutoffDate } | ForEach-Object {
    Remove-Item $_.FullName -Force
    Write-Output "Deleted file: $($_.FullName)"
}
Output
Deleted file: C:\Temp\oldfile1.txt Deleted file: C:\Temp\oldfile2.log
🔍

Dry Run

Let's trace deleting files older than 30 days in C:\Temp.

1

Calculate cutoff date

Current date is 2024-06-15; cutoff date is 2024-05-16 (30 days ago).

2

List files and check dates

File1 last modified 2024-04-10 (older), File2 last modified 2024-06-01 (newer).

3

Delete old files

Delete File1, keep File2.

File NameLast ModifiedDelete?
File1.txt2024-04-10Yes
File2.log2024-06-01No
💡

Why This Works

Step 1: Get-ChildItem lists files

The Get-ChildItem command fetches all files in the folder to check.

Step 2: Filter by last modified date

Using Where-Object, files older than the cutoff date are selected.

Step 3: Remove-Item deletes files

The Remove-Item command deletes each old file found.

🔄

Alternative Approaches

Using -Recurse to delete old files in subfolders
powershell
Get-ChildItem -Path $FolderPath -File -Recurse | Where-Object { $_.LastWriteTime -lt $CutoffDate } | Remove-Item -Force
Deletes old files in all subfolders too; use carefully to avoid unwanted deletions.
Using -WhatIf to simulate deletion
powershell
Get-ChildItem -Path $FolderPath -File | Where-Object { $_.LastWriteTime -lt $CutoffDate } | Remove-Item -WhatIf
Shows which files would be deleted without actually deleting them; good for testing.
Using a loop with Try-Catch for error handling
powershell
foreach ($file in Get-ChildItem -Path $FolderPath -File) { if ($file.LastWriteTime -lt $CutoffDate) { try { Remove-Item $file.FullName -Force; Write-Output "Deleted $($file.Name)" } catch { Write-Output "Failed to delete $($file.Name)" } } }
Provides error messages if deletion fails, improving robustness.

Complexity: O(n) time, O(1) space

Time Complexity

The script checks each file once, so time grows linearly with the number of files (O(n)).

Space Complexity

The script processes files one by one without extra storage, so space is constant (O(1)).

Which Approach is Fastest?

Using Get-ChildItem with filtering is efficient; adding recursion increases time but covers subfolders.

ApproachTimeSpaceBest For
Basic filter and deleteO(n)O(1)Simple folder cleanup
Recursive deletionO(n + m)O(1)Folders with subfolders
Loop with error handlingO(n)O(1)Robust deletion with feedback
💡
Always test your script with -WhatIf before actual deletion to avoid accidental data loss.
⚠️
Beginners often forget to filter only files and try deleting folders, causing errors.