Skip to content

Instantly share code, notes, and snippets.

@markwragg
Last active November 6, 2022 21:54
Show Gist options
  • Save markwragg/0eba99d2b99325a0e912f316065860ba to your computer and use it in GitHub Desktop.
Save markwragg/0eba99d2b99325a0e912f316065860ba to your computer and use it in GitHub Desktop.
Powershell script to remove files older than a certain date and log the files removed to a file.
[CmdletBinding()]
Param(
$limit = (Get-Date).AddDays(-7),
$path = "C:\Example\Path"
)
# Delete files older than the $limit.
$FilesToDelete = (Get-ChildItem -Path $path -Exclude Logs | Where-Object { $_.LastWriteTime -lt $limit }) | Select Path
# If files are deleted create a log detailing this
if($FilesToDelete){
Set-Content "$Path\Logs\$(get-date -uFormat "%d-%m-%Y %H-%M-%S").log" $FilesToDelete;
Remove-Item -Path $FilesToDelete -Force -Recurse
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment