Streamlined File Cleanup Script

In this post, we introduce a PowerShell script designed for streamlined file cleanup. This script identifies and removes unnecessary files from a specified directory based on their age, helping you maintain a tidy file system.
If you’re looking for efficient server management solutions, don’t forget to check out our software, ServerEngine, at https://serverengine.co. Lets dive into the script!
### Step 1: Define the Directory and Age Threshold
The first step is to specify the directory you want to clean and the age threshold for the files to be removed. Files older than this threshold will be deleted.

$directoryPath = 'C:\TempFiles'
$ageThresholdDays = 30
$thresholdDate = (Get-Date).AddDays(-$ageThresholdDays)

### Step 2: Find Files Older than the Threshold
Next, we will retrieve all files in the specified directory that are older than the age threshold we’ve set in the previous step. This helps us identify which files need to be deleted.

$oldFiles = Get-ChildItem -Path $directoryPath -File | Where-Object { $_.LastWriteTime -lt $thresholdDate }

### Step 3: Remove Old Files
We will now proceed to remove the identified old files, ensuring we clean up our specified directory. This is done with caution to prevent accidental deletion of important files.

if ($oldFiles.Count -gt 0) {
    foreach ($file in $oldFiles) {
        Remove-Item -Path $file.FullName -Force
        Write-Host "Deleted: $($file.Name)"
    }
} else {
    Write-Host "No files older than $ageThresholdDays days found in $directoryPath."
}

### Step 4: Summary of Cleanup Completion
Finally, we will output a summary message indicating the number of files deleted or confirming that no old files were found. This gives you clear feedback on what the script accomplished.

Write-Host "Cleanup process completed. $($oldFiles.Count) files were deleted from $directoryPath."

Feel free to customize the directory path and age threshold to suit your needs. Keep visiting our website for more useful PowerShell scripts to enhance your productivity!