Worklet: Example of a workflow to continue across reboots to fix corrupt Sophos install using scheduled tasks

This is something that I put together to fix corrupt installs of Sophos caused by our old imaging system. The logic could be used for any workflow that needs to span reboots and continue. I am attaching two executables and two PowerShell scripts to the worklet. The worklet then copies them to C:\Windows\Temp so they are not removed when the worklet completes and they can continue after reboot.

Eval code -I always want this to run on whatever target devices are selected

Exit 1

Remediation Code

#Create scheduled task to trigger script1 on next boot
$AtStartup = New-ScheduledTaskTrigger -AtStartup -RandomDelay 00:00:30
$Settings = New-ScheduledTaskSettingsSet
$Principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$Action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NonInteractive -NoLogo -NoProfile -ExecutionPolicy Bypass -File "c:\windows\temp\script1.ps1"'
$Task = New-ScheduledTask -Trigger $AtStartup -Settings $Settings -Action $Action -Principal $Principal
Register-ScheduledTask -TaskName "ResumeWorkflow1" -InputObject $Task

#Create DISABLED scheduled task to trigger script2 on subsequent boot
$Action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NonInteractive -NoLogo -NoProfile -ExecutionPolicy Bypass -File "c:\windows\temp\script2.ps1"'
$Task = New-ScheduledTask -Trigger $AtStartup -Settings $Settings -Action $Action -Principal $Principal
Register-ScheduledTask -TaskName 'ResumeWorkflow2' -InputObject $Task

Disable-ScheduledTask -TaskName ResumeWorkflow2

#Copy scripts and executables to windows\temp to run after reboots 
 Copy-Item -Path "sophossetup.exe" -Destination "c:\windows\temp"
 Copy-Item -Path "SophosZap.exe" -Destination "c:\windows\temp"
 Copy-Item -Path "script1.ps1" -Destination "c:\windows\temp"
 Copy-Item -Path "script2.ps1" -Destination "c:\windows\temp"
#Start first run of sophos zap and reboot
 Start-Process -FilePath 'c:\windows\temp\SophosZap.exe' -ArgumentList ('--confirm') -Wait
 Restart-Computer -Force


##Script1 .ps1
#Enable second scheduled task and remove first scheduled task
Enable-ScheduledTask -TaskName ResumeWorkflow2
Unregister-ScheduledTask -TaskName ResumeWorkflow1 -Confirm:$false
#Run Sophos Zap again to finish cleaning and reboot
Start-Process -FilePath 'c:\windows\temp\SophosZap.exe' -ArgumentList ('--confirm') -Wait
Restart-Computer -Force


##Script2 .ps1
#Remove second scheduled task
Unregister-ScheduledTask -TaskName ResumeWorkflow2 -Confirm:$false
#Reinstall Sophos and reboot
Start-Process -FilePath 'c:\windows\temp\sophossetup.exe' -ArgumentList ('--quiet') -Wait
Restart-Computer -Force