← script library

Scheduled Task Cleanup Script

Software DeploymentDecember 27, 2024

This PowerShell script simplifies the process of cleaning up old scheduled tasks on a Windows server. Regular maintenance of scheduled tasks is critical for ensuring optimal server performance and reducing clutter. Administrators utilizing ServerEngine can benefit from this script by keeping their scheduled tasks organized and efficient. The script allows users to specify a date threshold, deleting tasks that have not run since that date.

powershell
param (
    [int]$daysThreshold = 30
)
# Calculate the cutoff date
$cutoffDate = (Get-Date).AddDays(-$daysThreshold)
# Get scheduled tasks and filter by last run time
$oldTasks = Get-ScheduledTask | Where-Object { $_.LastRunTime -lt $cutoffDate -and $_.LastRunTime -ne $null }
foreach ($task in $oldTasks) {
    # Remove the old scheduled task
    Unregister-ScheduledTask -TaskName $task.TaskName -Confirm:$false
    Write-Output "Removed old scheduled task: $($task.TaskName)"
}
Write-Output "Scheduled task cleanup completed. Tasks older than $daysThreshold days have been removed."

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.