0

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
mklement0
  • 382,024
  • 64
  • 607
  • 775
Salah
  • 173
  • 3
  • 17

1 Answers1

1

You can disable a task like this:

Disable-ScheduledTask -TaskPath "\your-user\" -TaskName "your-task-name"

Add the above line to a text file and save it with ps1 extension. Then create a task on Task Scheduler. In the General tab (of properties window), make sure you check Run with highest privileges. The Action should be Start a program where the Program/script is Powershell.exe and the argument has a complete path to the ps1 file you created earlier (e.g. C:\Scripts\myTask.ps1).

Mahdi
  • 3,199
  • 2
  • 25
  • 35