ninja-one/set-scheduled-tasks.ps1
|
begin { } process { try { $script:containsErrors = $false Write-Host "Updating scheduled tasks..." -ForegroundColor Yellow # Delete the default scheduled tasks that install updates automatically $tasks = @( @{Name = "TVSUUpdateTask"; TaskPath = "\TVT\"; Action = "Disable" }, @{Name = "TVSUUpdateTask_UserLogOn"; TaskPath = "\TVT\"; Action = "Enable" }, @{Name = "EPSON*"; TaskPath = "\"; Action = "Disable" } ) # log the original tasks to be processed foreach ($task in $tasks) { $taskName = $task.Name $taskPath = $task.TaskPath $action = $task.Action Write-Host "Processing task: $taskPath$taskName - Action: $action" -ForegroundColor Gray } $scheduledTasks = @() foreach ($task in $tasks) { $taskName = $task.Name $action = $task.Action $taskPath = $task.TaskPath $tmpTask = Get-ScheduledTask -TaskName $taskName -TaskPath $taskPath -ErrorAction SilentlyContinue if ($null -ne $tmpTask) { $scheduledTasks += @{ Task = $tmpTask; Action = $action } } } foreach ($scheduledTask in $scheduledTasks) { $taskName = $scheduledTask.Task.TaskName $taskPath = $scheduledTask.Task.TaskPath $action = $scheduledTask.Action # Write-Host "Found task: $taskPath$taskName - Action: $action" -ForegroundColor Gray try { if ($action -eq "Disable") { $scheduledTask.Task | Disable-ScheduledTask -ErrorAction Stop Write-Host "Disabled task: $taskPath$taskName" -ForegroundColor Green } elseif ($action -eq "Enable") { $scheduledTask.Task | Enable-ScheduledTask -ErrorAction Stop Write-Host "Enabled task: $taskPath$taskName" -ForegroundColor Green } } catch { $script:containsErrors = $true Write-Error "Failed to $($action.ToLower()) task $taskPath$($taskName): $_" } } if ($script:containsErrors) { Write-Host "[ERROR] One or more tasks failed to be updated." -ForegroundColor Red exit 1 } exit 0 } catch { # output the error and the line it came from Write-Host "[ERROR]: $_" Write-Host "Line: $($_.InvocationInfo.ScriptLineNumber)" exit 1 } } end { } |