PowerShell: Remove folders older than x amount of days

Just another Tech site

PowerShell: Remove folders older than x amount of days

Trying to do a clean up of installation version folders for applications installed after x amount of days.  This will remove folders and files in subfolders older than 4 days  as scripted below.  Change the variables to help identify the folder locations.  Please run on a test system before using for production, just to make sure that you are targeting the correct folders to cleaned up.

$AppName = "Google"


# PowerShell Script: Remove folders older than 60 days and log deletions
# Path to search
#$BasePath = "Location of old folders per application\$($Appname)\"
$BasePath = "C:\InstallLocation"
# Log file path
$LogFile  = "C:\Logs\$($Appname)_fldr_removed.log"
# Age threshold in days
$DaysOld  = 4

# Ensure log directory exists
$logDir = Split-Path $LogFile
if (-not (Test-Path $logDir)) {
    New-Item -Path $logDir -ItemType Directory -Force | Out-Null
}

# Write header to log
"=== Folder Cleanup Started: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ===" | Out-File -FilePath $LogFile -Encoding UTF8 -Append

try {
    # Get all folders in the base path
    $folders = Get-ChildItem -Path $BasePath -Directory -ErrorAction Stop

    foreach ($folder in $folders) {
        # Check folder age
        if ($folder.LastWriteTime -lt (Get-Date).AddDays(-$DaysOld)) {
            try {
                # Remove folder and all contents
                Write-Output "Would remove: $($folder.FullName)"
                #Remove-Item -Path $folder.FullName -Recurse -Force -ErrorAction Stop # -WhatIf

                # Log success
                "Removed: $($folder.FullName) | LastWriteTime: $($folder.LastWriteTime)" | Out-File -FilePath $LogFile -Encoding UTF8 -Append
            }
            catch {
                # Log failure
                "ERROR removing: $($folder.FullName) | $_" | Out-File -FilePath $LogFile -Encoding UTF8 -Append
            }
        }
    }
}
catch {
    "ERROR accessing base path: $BasePath | $_" | Out-File -FilePath $LogFile -Encoding UTF8 -Append
}

"=== Folder Cleanup Finished: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ===`n" | Out-File -FilePath $LogFile -Encoding UTF8 -Append