Dec 24

Restart Computers in Sequential Order

Restarting servers is a necessary evil in a Windows administrator’s world.  Unfortunately, you cannot not always just restart servers during maintenance as they may have a service dependent on another server.  Due to this, you may need to restart your servers in sequential order.  Luckily, powershell 3.0 makes this quite easy using the restart-computer commandlet.  Please note, the restart-computer commandlet added several important parameters vs the 2.0 version, which includes the following (Good Explanation Here):

  • -Delay
  • -For
  • -Timeout
  • -Wait

The above parameters allow you to ensure a server rebooted before moving on in the script.  For a full description, see Restart-Computer on TechNet

For our script, we will use a CSV file that lists the server names and the sequence to group them for restarting (Yes we can have multiple servers in the same sequence number).  Our powershell script will then read in the the servers.csv, group the servers by their sequence number, and reboot the servers according to the sequence number group.  The below powershell script will wait until the servers have fully rebooted before moving to the next sequence number to reboot.  You may wish to modify the restart-computer parameters to suit your needs.  Additionally, you will need to modify the $filePath and $creds variables accordingly.

SERVERS.CSV

SERVER,SEQUENCE
ad1,1
ad2,2
web,2
sql,2
printers,3
files,3
app,4

 RESTART_SEQUENTIAL_ORDER.PS1

#=========================================================================
# Restart_Sequential_Order.ps1
# VERSION: 1.0
# AUTHOR: Brian Steinmeyer
# EMAIL: sigkill@sigkillit.com
# WEB: http://sigkillit.com
# DATE: 12/24/2014
# REQUIREMENTS:
# 1) Powershell 3.0 for the following parameters:
#    -Delay
#    -For
#    -Timeout
#    -Wait
# COMMENTS: This script restarts servers in sequential order and does not
# not start the next sequence until the previous server(s) rebooted.
#=========================================================================
 
# ------ SCRIPT CONFIGURATION ------
$filePath = "servers.csv"
$creds = get-credential domain\user
# ------ END CONFIGURATION ------
$data = Import-Csv $filePath 
$objdata = $data | Select SERVER,SEQUENCE | Group SEQUENCE | Select @{n="SEQUENCE";e={$_.Name}},@{n="SERVER";e={$_.Group | ForEach{$_.SERVER}}} | Sort SEQUENCE
ForEach ($d in $objdata) {
	$sequence = $d.SEQUENCE.ToString()
	$server = $d.SERVER.ToString()
	write-host "SEQUENCE: $sequence"
	write-host "------------"
	write-host "Rebooting: $server"
	restart-computer -ComputerName "$server" -Force -Wait -Credential $creds
}