Sunday, May 8, 2016

Restart Computers Remotely via PowerShell

To restart a remote computer, you need to run the command with credentials that have the right privileges to remotely shut down a computer, typically an admin account. Assuming my current credentials were adequate, I could easily reboot the computer SERVER01:
PS C:\> Restart-Computer Server01 -whatif
What if: Performing operation "Restart-Computer" on Target " (Server01)".
although I didn't really; I took advantage of the -WhatIf parameter to verify my command. This is especially helpful if I'm rebooting a bunch of servers:
PS C:\> restart-computer "server01","server02","server03" -whatif
By the way, here's how you could shut down a list of computers:
PS C:\> restart-computer (get-content c:\work\computers.txt)
Because the cmdlet is using WMI objects and methods under the hood you can specify alternate credentials, either a saved credential object or a user name:
PS C:\> restart-computer (get-content c:\work\computers.txt) -credential "mycompany\administrator"
I'll get prompted for the password, but then this credential will be used for every computer in the list.
The Restart-Computer cmdlet will fail, if a logon session is detected. PowerShell will raise an exception. However, you can force a reboot using -- what else? -- the -force parameter. Be aware this will force applications to close with the potential loss of unsaved work.
Another option for rebooting or even logging off is to use the Win32_OperatingSystem WMI Class and the Win32ShutDown method. I recommend using Invoke-WMIMethod because it supports -WhatIf and -Confirm. I found it just as easy to pipe a WMI object from Get-WMIObject to Invoke-WMIMethod:
PS C:\> Get-WmiObject win32_operatingsystem -ComputerName Quark | Invoke-WMIMethod -name Win32Shutdown
The Win32Shutdown method can accept parameters. The default is 0 which means do a simple logoff. But if the user has open files or if the default method fails, you can always resort to a forceful logoff:
PS C:\> Get-WmiObject win32_operatingsystem -ComputerName Quark | Invoke-WMIMethod -name Win32Shutdown -ArgumentList @(4)