Mass reboot servers and workstations with PowerShell

We’ve got a bunch of servers stuck in pending reboot state due to SCCM updates. There is no way I’m rebooting 50 servers manually! PowerShell to the rescue!

Sponsors, article continues below...

1) First step is to get a list of the machines to be rebooted into a CSV.

2) Fire up a PowerShell with a domain account that has local admin rights on the target machines.

3) Set the header if you did not put a header in the CSV file.

1
$header = "server"

4) Set $servers equal to an array of server names to be rebooted.

1
$servers = import-csv c:\path\to\ServersToReboot.csv -header $header

5) Issue reboots using a foreach loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
foreach($i in $servers) {
     Write-Host "Attempting to reboot:" $i.server "..."
 
     $serverObj = gwmi Win32_operatingsystem -computer $i.server
 
     $status = $serverObj.reboot()
 
     if ($status.ReturnValue = "0") {
          Write-Host "Reboot successful."
     } else {
          Write-Host "Reboot failed. Check permissions."
     }
}

Here is an example of all the code together:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$header = "server"
 
$servers = import-csv c:\path\to\ServersToReboot.csv -header $header
 
foreach($i in $servers) {
     Write-Host "Attempting to reboot:" $i.server "..."
 
     $serverObj = gwmi Win32_operatingsystem -computer $i.server
 
     $status = $serverObj.reboot()
 
     if ($status.ReturnValue = "0") {
          Write-Host "Reboot successful."
     } else {
          Write-Host "Reboot failed. Check permissions."
     }
}

Piece of cake!

This entry was posted in Microsoft, PowerShell.

Leave a Reply