Ever wanted to start a scheduled task within a powershell script? Well, you sure can!
In my case, our systems have a scheduled task that's run every day after work. However, users requested the ability to do this themselfs instead of shooting the IT department a request and then wait for them to start the task.
The only requirement is that you supply admin credentials inside the script because remotely starting a schedule task requires admin rights.
You can do two things here to give users the ability to start the task
- Add the users/group to the local admin group on the server where the schedule task resides
(Any sane IT person would strongly recommend you to NOT do this, but if your situation leaves you no other choice...) - Set the admin credentials inside the Powershell script
Because the users are most likely starting the script from their personal computers, you have to remote call the scheduled task to start. To do this, you have to use Invoke-Command.
The command would basically look like this: Invoke-Command -ComputerName '(servername)' -ScriptBlock {schtasks /run /tn "(name of task"} -credential $credential
Another thing that might be usefull is monitoring the status of the task. You can query the current status of the task using the same Invoke-Command.
The command would then look like this: Invoke-Command -ComputerName '(server)' -ScriptBlock { ((schtasks /query /TN "(name of task")[4] -split ' +')[5]} -credential $credential
The reason for the Split command is that in my case the column that contains the status varies per task, sometimes it's in 5th and sometimes 4th. Experiment yourself and find out.
And that's all to it really.
You can find an example of my own script in my Github here: https://github.com/MoebiusZero/Scripts/blob/main/Powershell/RunTaskRemote.ps1
Most probally you don't need the whole menu thing, but you can basically just strip the Do and Until blocks out and use it for your own scripts.