Powershell – Schtasks — what is wrong with the following command

powershelltask-schedulerwindows 7

The following script schedules successfully but will not actually, you know, restart the server.

schtasks /create /tn "restart test" /ru "domain\admin" /rp supersecret /sc once /st 11:35 /tr "PowerShell -command {Restart-Computer -ComputerName server01 -force -wait
Send-MailMessage -From mail1@domain.com -To mail2@domain.com -Subject 'Rebooted' -SmtpServer smtp.domain.com}"

The Task Scheduler event logs show the task completed successfully:

Task Scheduler successfully completed task "\restart test" , instance "{4a8b0e75-eb2f-4be6-918d-7b66473dd344}" , action "C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.EXE" with return code 0.

If I run just the commands within {...}, it will restart the server and send the notification email.

What am I missing?

EDIT: I am executing this from a Windows 7 laptop with PowerShell 3.0 to a Windows 2012 Server

Best Answer

OK, I'm deleting my earlier comments, and moving my comments into an answer, since at first my comments started as just general advice, but they turned into heavy clarification with an exact answer.

So I tested with Win7 and PS3, so I'm using the same platform as you.

Firstly, just remove the -Command { ... } from your command, and by that I mean this:

schtasks /create /tn "restart test" /ru "domain\admin" /rp supersecret /sc once /st 11:35 /tr "PowerShell Restart-Computer -ComputerName server01 -force -wait" 

That works. But your next problem is that you want to execute multiple commands, (1 restart the computer and 2 send an email,) and for that I would recommend putting the commands in a ps1 script file and instead making the task like this:

schtasks /create /tn "restart test" /ru "domain\admin" /rp supersecret /sc once /st 11:35 /tr "PowerShell C:\Scripts\restartAndEmail.ps1"

I'm not saying you couldn't technically get two Powershell commands to run in a single call to schtasks, but it's unwieldy and you have to start worrying about characters that need to be escaped on the command line such as the | character, etc., and it just becomes easier from almost every perspective to just use a ps1 file instead.

It's important that you specify the fully-qualified path to the script. The current working directory of the scheduled task will probably not be the same as the path of the script, so relative path won't cut it.

In fact, when I'm making scheduled tasks for Powershell scripts, I typically include the full path to the Powershell exe as well, just to be sure. Those we have already demonstrated here that you don't have to include the fully qualified path to Powershell.exe in this scenario.