Skip to content

Latest commit

 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

Windows Recent Folder Cleaner

A secure, automated PowerShell script that monitors and cleans the Windows Recent folder by logging detailed metadata about shortcut (.lnk) files before backing them up and deleting them. Designed for forensic analysis and system maintenance with enterprise-grade security features.

Overview

The Windows Recent Folder Cleaner consists of two main components:

WindowsRecentFolderCleaner.ps1

The core PowerShell script that:

  • Automatically creates a scheduled task to run every 5 minutes
  • Scans the Windows Recent folder for .lnk files
  • Extracts comprehensive metadata from each shortcut
  • Logs all data to a secure JSON database
  • Creates backups of files before deletion
  • Implements multiple security layers including hash verification and ACL restrictions
  • Provides detailed console output and notifications

WindowsRecentFolderCleaner.cmd

A batch file wrapper that:

  • Bypasses PowerShell execution policy restrictions
  • Launches the script with elevated administrator privileges
  • Ensures the script runs in a controlled environment

Features

Core Functionality

  • Automated Monitoring: Runs every 5 minutes via Windows Task Scheduler
  • Comprehensive Logging: Captures 25+ metadata fields per shortcut file
  • Secure Deletion: Backs up files before permanent removal
  • JSON Database: Maintains a searchable log of all processed files
  • Error Handling: Robust error recovery and cleanup procedures

Security Features

  • Script Integrity Verification: SHA256 hash checking on every run
  • Access Control: Restricts file permissions to current user only
  • Tamper Detection: Alerts on unauthorized script modifications
  • Path Validation: Prevents symlink and path injection attacks
  • Administrator Enforcement: Requires elevated privileges for operation

Metadata Collection

For each .lnk file, the script logs:

  • File system attributes (size, timestamps, owner, hash)
  • Shortcut properties (target path, arguments, working directory)
  • Target file information (if accessible)
  • Processing metadata (computer name, username, timestamps)
  • Alternate data streams and security attributes

Requirements

System Requirements

  • Windows 10/11 (64-bit recommended)
  • PowerShell 5.1 or higher
  • Administrator privileges
  • At least 100MB free disk space for logs and backups

Permissions

  • Local Administrator rights
  • Write access to the script directory
  • Access to Windows Task Scheduler
  • Read/write access to Windows Recent folder

Installation

  1. Download Files: Place both WindowsRecentFolderCleaner.ps1 and WindowsRecentFolderCleaner.cmd in the same directory (e.g., C:\Tools\)

  2. Initial Setup: Run the script once to create the scheduled task and initialize security files

  3. Verify Installation: Check that the following files are created:

    • WindowsRecentFolderCleaner.hash (script integrity hash)
    • WindowsRecentFolderCleaner.hash.meta (metadata)
    • logs\ directory
    • Scheduled task named "WindowsRecentFolderCleaner_Monitor"

Usage

Method 1: Using the Wrapper (Recommended)

For systems with execution policy restrictions:

WindowsRecentFolderCleaner.cmd

This method:

  • Automatically bypasses execution policy
  • Requests administrator privileges
  • Runs the script in a secure environment

Method 2: Manual PowerShell Execution

If you have execution policy permissions:

# Open PowerShell as Administrator, then run:
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\WindowsRecentFolderCleaner.ps1

Method 3: Direct Execution (if policy allows)

If your system allows script execution:

# Run as Administrator:
.\WindowsRecentFolderCleaner.ps1

How It Works

First Run Process

  1. Privilege Check: Verifies administrator rights
  2. Environment Validation: Checks paths and system compatibility
  3. Hash Generation: Creates SHA256 hash of the script for integrity
  4. Task Creation: Registers a scheduled task to run every 5 minutes
  5. Security Setup: Applies ACL restrictions to critical files
  6. Initial Scan: Processes existing .lnk files

Subsequent Runs

  1. Integrity Verification: Compares current script hash with stored hash
  2. Task Validation: Ensures scheduled task exists and is enabled
  3. File Discovery: Scans Recent folder for new .lnk files
  4. Metadata Extraction: Parses each shortcut using Windows Shell COM objects
  5. Database Update: Appends new records to JSON log
  6. Backup Creation: Copies files to backup directory
  7. Secure Deletion: Permanently removes original files
  8. Cleanup: Validates all operations and reports status

Scheduled Task Details

  • Name: WindowsRecentFolderCleaner_Monitor
  • Frequency: Every 5 minutes
  • Action: Runs PowerShell with RemoteSigned execution policy
  • Principal: Current user with highest privileges
  • Settings: Runs on battery, doesn't stop on battery, starts when available

File Structure

After installation, the following files are created:

C:\Tools\
├── WindowsRecentFolderCleaner.ps1          # Main script
├── WindowsRecentFolderCleaner.cmd          # Wrapper launcher
├── WindowsRecentFolderCleaner.hash         # Script integrity hash
├── WindowsRecentFolderCleaner.hash.meta    # Hash metadata (JSON)
├── logs\
│   ├── WindowsRecentFolderCleaner.json     # Main log database
│   ├── WindowsRecentFolderCleaner.json.hash # Log integrity hash
│   └── backups\                             # Backup directory
│       ├── File1.lnk_20231201_143022.bak
│       └── File2.lnk_20231201_143023.bak
└── README.md                               # This documentation

Log Rotation

  • JSON logs rotate when exceeding 100MB
  • Old logs are timestamped and archived
  • Backups are retained indefinitely (manual cleanup required)

Security Features

Script Integrity

  • SHA256 hash verification on every execution
  • Tamper detection with alert notifications
  • Restricted file permissions (owner-only access)

Data Protection

  • Atomic file operations to prevent corruption
  • Backup-before-delete policy
  • JSON integrity validation
  • Path length validation (260 char limit)

Access Control

  • Administrator privilege enforcement
  • ACL restrictions on sensitive files
  • User SID-based permission management

Troubleshooting

Common Issues

"Running scripts is disabled on this system"

Solution: Use WindowsRecentFolderCleaner.cmd instead of running the .ps1 directly.

"This script requires administrator privileges"

Solution: Right-click the launcher and select "Run as administrator", or use the wrapper which requests elevation.

"Scheduled task creation failed"

Cause: Insufficient permissions or Group Policy restrictions. Solution:

  • Ensure you're running as Administrator
  • Check Group Policy for task scheduler restrictions
  • Manually create the task if needed

"Script integrity check failed"

Cause: Script file has been modified. Solution:

  • Verify the script hasn't been tampered with
  • Delete .hash and .hash.meta files to reset (will recreate on next run)
  • Contact administrator if tampering is suspected

"JSON file integrity check failed"

Cause: Log file corruption. Solution:

  • Check disk space and file system health
  • Restore from backup if available
  • Delete corrupted JSON file (will start fresh)

Error Codes

  • Exit Code 0: Success
  • Exit Code 1: Critical error (check logs)

Logs and Debugging

  • All operations are logged to console with color-coded output
  • JSON database contains detailed processing information
  • Backup files preserve original shortcuts for analysis

Uninstallation

  1. Stop the Scheduled Task:

    Unregister-ScheduledTask -TaskName "WindowsRecentFolderCleaner_Monitor" -Confirm:$false
  2. Remove Files:

    Remove-Item -Path "C:\Tools\WindowsRecentFolderCleaner.*" -Force
    Remove-Item -Path "C:\Tools\logs" -Recurse -Force
  3. Clean Registry (if needed):

    • No registry entries are created by this script

Advanced Configuration

Modifying Schedule

To change the run frequency (default: 5 minutes):

  1. Open Task Scheduler
  2. Find "WindowsRecentFolderCleaner_Monitor"
  3. Modify the trigger settings

Custom Log Location

The script uses relative paths. To change locations, modify these variables in the script:

  • $LogsDirectory
  • $BackupDirectory

Backup Retention

Currently, backups are kept indefinitely. Add cleanup logic if needed.

Support and Contributing

Reporting Issues

When reporting problems, include:

  • Full error messages
  • PowerShell version ($PSVersionTable)
  • Windows version
  • Contents of logs\WindowsRecentFolderCleaner.json (last few entries)

Security Considerations

  • This script requires administrator privileges
  • It permanently deletes files from the Recent folder
  • Always review the code before running on production systems
  • Test in a virtual environment first

License

This script is provided as-is for educational and maintenance purposes. Use at your own risk. MIT License

About

A secure, automated PowerShell script that monitors and cleans the Windows Recent folder by logging detailed metadata about shortcut (.lnk) files before backing them up and deleting them. Designed for forensic analysis and system maintenance with enterprise-grade security features.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages