← script library

Streamline Your File Management with a PowerShell Directory Cleanup Script

Files & FoldersJanuary 5, 2025

In this article, we will develop a professional PowerShell script designed to manage and clean up files in a specified directory. This script will help improve your file organization, delete unnecessary files, and log actions for future reference.

powershell
# Define parameters
param (
    [string]$directoryPath = "C:\temp",  # Set the default directory
    [int]$ageThresholdDays = 30            # Files older than 30 days will be deleted
)
# Check if the directory exists
if (-Not (Test-Path $directoryPath)) {
    Write-Host "ERROR: The specified directory does not exist."
    return
}

# Get all files in the specified directory
$files = Get-ChildItem -Path $directoryPath -File
# Get the current date for comparison
$currentDate = Get-Date
# Filter files based on age threshold
$filesToDelete = $files | Where-Object {
    ($currentDate - $_.LastWriteTime).Days -gt $ageThresholdDays
}

# Log file to store deleted file names
$logFilePath = "C:\temp\deleted_files.log"
# Check if there are files to delete
if ($filesToDelete.Count -eq 0) {
    Write-Host "No files older than $ageThresholdDays days were found."
} else {
    foreach ($file in $filesToDelete) {
        try {
            # Remove the file
            Remove-Item -Path $file.FullName -Force
            # Log the deletion
            Add-Content -Path $logFilePath -Value "Deleted: $($file.FullName) on $(Get-Date)"
            Write-Host "Deleted: $($file.FullName)"
        } catch {
            Write-Host "ERROR: Unable to delete file $($file.FullName): $_"
        }
    }
}

# Final summary output
Write-Host "Cleanup completed. Review the log file at $logFilePath for details."

Run it across your fleet

This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.

Ready when you are.

Try ServerEngine free for 7 days.