For a script I have that maintains our systems and installs new versions of our web code, I have the occassional need to also reboot a server during after that install. Like most things programming, there are several ways to script a reboot.
This first example (my preferred method) reboots a remote system.
$objServerOS = gwmi win32_operatingsystem -computer servername
Leave off the “-computer servername” to reboot the local system.
This second method is similar. The following lines will reboot the local system, force the reboot of the local system, or reboot a remote system.
(gwmi win32_operatingsystem -ComputerName Server).Win32Shutdown(6)
Here is a list of the codes that can be used.
0 -Log Off
4 -Forced Log Off
5 -Forced Shutdown
6 -Forced Reboot
8 -Power Off
12 -Forced Power Off
Pipe $objServerOS or (gwmi win32_operatingsystem) to Get-Member to see more goodies.
There is a good chance the above commands will error when trying to do a reboot, complaining about privileges not held, even if you’re running as admin. Add a privs enable line in between the above two, and it will process just fine.
$objServer = gwmi win32_operatingsystem
$objServer.psbase.Scope.Options.EnablePrivileges = $true