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
$objServerOS.reboot()
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).Win32Shutdown(2)
(gwmi win32_operatingsystem).Win32Shutdown(6)
(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
1 -Shutdown
5 -Forced Shutdown
2 -Reboot
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
$objServer.reboot()
i would really like to be able to reboot machines remotely from a text file. CAn you help. This is what I have and this is the error I get.
$a = Get-Content “C:\serverlist.txt”
foreach ($i in $a)
{
(gwmi win32_operatingsystem -Credential $cred -ComputerName $a).Win32Shutdown(6)
}
ERROR:
Method invocation failed because [System.Object[]] doesn’t contain a method named ‘Win32Shutdown’.
At :line:24 char:77
+ (gwmi win32_operatingsystem -Credential $cred -ComputerName $a).Win32Shutdown
Change -computername $a to $i
Final Product:
$a = Get-Content “C:\serverlist.txt”
foreach ($i in $a)
{
(gwmi win32_operatingsystem -Credential $cred -ComputerName $i).Win32Shutdown(6)
}
This worked for me!
Is there any way to add reboot comments before the reboot ? which can be later seen in the event viewer..
Are the numbers after the shutdown command indicating what to write to the event log? I need to specify a reason fore reboot.