Skip to content

directory_cleanup.ps1

Corey Watson edited this page Dec 24, 2025 · 2 revisions

directory_cleanup.ps1

Cleans up files and directories older than a specified number of days.

Overview

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.

Purpose

Cleans up files and directories older than a specified number of days. Logs deleted items to a file.

Prerequisites

  • Windows operating system
  • PowerShell 5.1 or later
  • Administrator privileges (recommended for system directories)
  • Write access to target directory for log file creation

Configuration

Required Inputs

  • $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).

Behavior

  1. Initializes a log file (deleted_files.log) in the target directory
  2. Scans the specified folder and all subfolders for files
  3. Identifies files where last modified date is older than the specified number of days
  4. Logs each file deletion with filename and last modified timestamp
  5. Removes identified files
  6. Scans for empty directories after file cleanup
  7. Removes empty directories and logs the deletions
  8. Writes completion summary to the log file

Security Notes

  • Script uses strict mode and stops on errors ($ErrorActionPreference = 'Stop')
  • All file deletions are logged with timestamps for audit purposes
  • Uses -Force parameter for file and directory removal
  • Log file is created in the target directory, not a separate location

Exit Codes

  • Exit codes are not explicitly defined in this script
  • Script will terminate on errors due to $ErrorActionPreference = 'Stop'

Example Output

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.

Version History

  • 1.0.0 - Initial release

Links

Clone this wiki locally