PowerShell - Restart-Computer doesn't work as scheduled task

3

1

I have a Windows Server 2012 R2 (PowerShell 4). There is a ps1 file with a PowerShell script, which contains among other things the command restart-computer. I also created a cmd file which should be started via Task Scheduler.

  • Everything works as expected when I start the cmd file by double-clicking it.
  • Nearly everything works as expected except the reboot when the cmd is started via Windows Task Scheduler.

So I created a ps1 file which only executes restart-computer and a proper cmd file for testing purposes. I also tried Restart-Computer -AsJob

powershell.exe -ExecutionPolicy Bypass -File "C:\restart-computer123.ps1"

I also created the scheduled task configured for "Windows Server 2012 R2", with administrative credentials, highest privileges. and saved the password.

There is no error message in the event log or scheduler, but the server isn't rebooting.

What am I missing or doing wrong?

StefanK

Posted 2016-09-27T14:02:47.980

Reputation: 53

under what useraccount does the task run, what else is in the powershell script? – Kage – 2016-09-27T14:18:09.403

It runs as local "Administrator". There's nothing else in the "testing" powershell script. – StefanK – 2016-09-27T14:33:37.237

@StefanK what i'd do to troubleshoot this issue: export the whole $error Variable at the end of your script to a file. maybe also export something to a file before the restart-computer part. if nothing gets created, your script doesn't run. if the error get's exported, you have the error message inside your exported file. – SimonS – 2016-09-27T15:18:13.027

@SimonS writing the $error variable to a file brings light to the problem! There was an error, that there are other users logged on, and therefor it can't restart. With the "-Force" option it works! With the "-AsJob" option there's no error message, but also no reboot. – StefanK – 2016-09-28T05:12:08.623

@StefanK ok nice. -AsJob gave no error message/output because it's in a background thread. if you're intrested, here's more information: http://www.howtogeek.com/138856/geek-school-learn-how-to-use-jobs-in-powershell/

– SimonS – 2016-09-28T05:45:47.203

@StefanK You can answer your own question - you should turn your comment into an answer.

– DavidPostill – 2016-09-28T08:57:38.467

Answers

2

Writing the $error variable to a file brings light to the problem!

$error | Out-File C:\error.txt

There was an error, that there are other users logged on, and therefor it can't restart. With the "-Force" option it works.

Thank you SimonS to get me on the right track!

StefanK

Posted 2016-09-27T14:02:47.980

Reputation: 53