-
Notifications
You must be signed in to change notification settings - Fork 5
directory_cleanup.ps1
Corey Watson edited this page Dec 24, 2025
·
2 revisions
Cleans up files and directories older than a specified number of days.
This script provides automated cleanup functionality for directories by removing files older than a configurable threshold. All deletion operations are logged to maintain an audit trail of removed items.
Cleans up files and directories older than a specified number of days. Logs deleted items to a file.
- Windows operating system
- PowerShell 5.1 or later
- Administrator privileges (recommended for system directories)
- Write access to target directory for log file creation
-
$folderPath: The path to the folder to clean up -
$days: The number of days old a file must be to be deleted
These inputs must be provided via runtime variables ($runtime_folderPath and $runtime_days).
- Initializes a log file (
deleted_files.log) in the target directory - Scans the specified folder and all subfolders for files
- Identifies files where last modified date is older than the specified number of days
- Logs each file deletion with filename and last modified timestamp
- Removes identified files
- Scans for empty directories after file cleanup
- Removes empty directories and logs the deletions
- Writes completion summary to the log file
- Script uses strict mode and stops on errors (
$ErrorActionPreference = 'Stop') - All file deletions are logged with timestamps for audit purposes
- Uses
-Forceparameter for file and directory removal - Log file is created in the target directory, not a separate location
- Exit codes are not explicitly defined in this script
- Script will terminate on errors due to
$ErrorActionPreference = 'Stop'
Log file content example:
Cleanup Log - 12/1/2025 10:30:00 AM
-----------------------------------
Deleted: C:\Temp\oldfile1.txt - Last Modified: 11/1/2025 3:45:00 PM
Deleted: C:\Temp\oldfile2.log - Last Modified: 10/15/2025 8:20:00 AM
Deleted Directory: C:\Temp\EmptyFolder
Cleanup completed. Files and directories older than 30 days have been removed from C:\Temp.
- 1.0.0 - Initial release
- View Script Source
- Scripts - Back to script index