Files
management-scripts/Remove-OldFiles.ps1
T

14 lines
821 B
PowerShell
Raw 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 ) {
LogMsg "Deleting all items older than ${OlderThanDays} days in ""${Path}"""
$files = Get-ChildItem $Path | Where { !$_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-${OlderThanDays}) }
Foreach ( $f in $files ) {
$msg = "Deleting {0}" -f $f.FullName ; LogMsg $msg
Try { Remove-Item $f -Force | Out-Null }
Catch { LogErr $_.Exception.Message }
}
} Else { LogMsg "Path does not exist: ""${Path}""" }
} Else { LogMsg "The value entered for ""OlderThanDays"" is not an integer" }