PowerShell - Restart-Computer doesn't work as scheduled task
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
Updated on September 18, 2022Comments
-
StefanK over 1 year
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 triedRestart-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?
-
Kage over 7 yearsunder what useraccount does the task run, what else is in the powershell script?
-
StefanK over 7 yearsIt runs as local "Administrator". There's nothing else in the "testing" powershell script.
-
SimonS over 7 years@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 therestart-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. -
StefanK over 7 years@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.
-
SimonS over 7 years@StefanK ok nice.
-AsJob
gave no error message/output because it's in a background thread. if you're intrested, here's more information: howtogeek.com/138856/… -
DavidPostill over 7 years@StefanK You can answer your own question - you should turn your comment into an answer.