Effortless PowerShell Script to Monitor Disk Space and Automatically Clean Up Files When Usage Exceeds 70%

PowerShell Script

PowerShell

# Parameters

$driveLetter = “C:” # Specify the drive letter to monitor
$threshold = 70 # Set the disk usage threshold percentage
$folderToClean = “C:Temp” # Specify the folder from which files will be deleted
$logFile = “C:TempCleanupLog.txt” # Specify the log file location

# Function to log messages

function Log-Message {
param ([string]$message)
$timestamp = Get-Date -Format “yyyy-MM-dd HH:mm:ss”
Add-Content -Path $logFile -Value “$timestamp – $message”
}

# Get disk space information

$disk = Get-PSDrive -Name $driveLetter.Substring(0,1)
if ($disk) {
$usedPercentage = ($disk.Used / $disk.Used + $disk.Free) * 100
$usedPercentage = [math]::Round($usedPercentage, 2)

Log-Message “Drive $driveLetter usage: $usedPercentage%.”

if ($usedPercentage -ge $threshold) {
Log-Message “Disk usage exceeded $threshold%. Starting cleanup in $folderToClean.”

if (Test-Path $folderToClean) {
$files = Get-ChildItem -Path $folderToClean -File
foreach ($file in $files) {
try {
Remove-Item -Path $file.FullName -Force
Log-Message “Deleted file: $($file.FullName)”
} catch {
Log-Message “Error deleting file: $($file.FullName). $_”
}
}
Log-Message “Cleanup completed.”
} else {
Log-Message “Folder $folderToClean does not exist.”
}
} else {
Log-Message “Disk usage is below the threshold. No cleanup needed.”
}
} else {
Log-Message “Drive $driveLetter not found.”
}

Check out Latest Blogs – Click Here

Check out LinkedIn page – click Here 

PowerShell