I have a scheduled task in EC2 windows server 2019 that runs on start and I would like to delete after it finishes. I tried to schedule a task to delete it but the task kept running without deleting the other one, but the scripts work from Powershell directly.
SCHTASKS /Delete /TN AfterRestartSetup /F
I tried to add /z to delete the task right after it is done but it did not work.
schtasks /create /tn "AfterRestartSetup" /sc onstart /z /rl highest /ru system /tr "powershell.exe -file C:\scripts\setup\AfterRestartSetup.ps1"
I also tried to unregister but it didn't work also:
Unregister-ScheduledTask -TaskName "AfterRestartSetup" -Confirm:$false
You can disable a task like this:
Add the above line to a text file and save it with
ps1extension. Then create a task on Task Scheduler. In the General tab (of properties window), make sure you checkRun with highest privileges. The Action should beStart a programwhere the Program/script isPowershell.exeand the argument has a complete path to theps1file you created earlier (e.g. C:\Scripts\myTask.ps1).