Files

14 lines
857 B
PowerShell
Raw Permalink Normal View History

2021-10-01 17:57:35 -04:00
## This script will delete all files in a directory which are older than the specified number of days.
## It will not search recursively for files and will only look in the directory specified.
If ( $OlderThanDays -is [int] ) {
If ( Test-Path $Path ) {
2023-10-05 13:11:38 -04:00
Write-Output "Deleting all items older than ${OlderThanDays} days in ""${Path}"""
2023-10-05 13:19:25 -04:00
$files = Get-ChildItem $Path | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-${OlderThanDays}) }
2021-10-01 17:57:35 -04:00
Foreach ( $f in $files ) {
2023-10-05 13:11:38 -04:00
$msg = "Deleting {0}" -f $f.FullName ; Write-Output $msg
2021-10-01 17:57:35 -04:00
Try { Remove-Item $f -Force | Out-Null }
2023-10-05 13:17:18 -04:00
Catch { Write-Error $_.Exception.Message }
2021-10-01 17:57:35 -04:00
}
2023-10-05 13:11:38 -04:00
} Else { Write-Output "Path does not exist: ""${Path}""" }
} Else { Write-Output "The value entered for ""OlderThanDays"" is not an integer" }