PowerShell Ezine, Logon Scripts

Guy's Scripting Ezine 45 - VBS Shutdown

Contents for Guy's Scripting Ezine 45 - VBS Shutdown

 ♣

This Week's Secret

As you may know, I am not a great one for disclaimers. Moreover, the whole nature of scripting is such that occasionally, mistakes just happen. In fact, the road to a successful script is littered with cast-offs. Therefore, it may come as a surprise when I say: 'This week take great care, this script could annoy people, or worse, you could shoot yourself in the foot and shutdown your own machine unexpectedly.' I will let you into a secret, I often forget the /s switch, which is vital for a shutdown and as a result my first effort does not work.

Example 1 VBScript to Shutdown a Computer

Scenario

Suppose that you need to restart a machine in a distant office.  By the time you walk down the corridor and reach the server room, you would like the domain controller to have rebooted.

What we are going to do is employ a VBScript to open up a DOS box, then instruct sendkeys to type in a command which will restart a computer.  But first, in order to get the correct machine name, the script generates an input box where you enter the name of the machine you wish to shut down.

Strongly recommended.

Before you rush off and try the script, take the time to familiarise yourself with the rich variety of 'shutdown' switches.  Go to the CMD prompt on a Windows Server 2003 or XP computer and then type shutdown /?  For instance, be aware that this command will either shutdown or restart.  Furthermore shutdown works on either a local or a remote machine.  Naturally, you need to be an administrator to execute shutdown successfully.

Here is your 'Get out of jail card'.  WHEN TESTING, if the script does NOT abort the shutdown, you have 60 seconds manually cancel by typing:
Shutdown /a /m \\ computername.

Example 1a - The Superior Version by Josh Murray

' Shutdown.vbs
' Example VBScript to Shutdown computers
' Author Josh Murray
' Version 4.1 - February 2007
' --------------------------------------Option Explicit
Dim objShell, strComputer, strInput
Dim strShutdown

Do
strComputer = (InputBox(" ComputerName to shutdown", "Computer Name"))
If strComputer <> "" Then
  strInput = True
End if
Loop until strInput = True

strShutdown = "shutdown -s -t 0 -f -m \\" & strComputer
    set objShell = CreateObject("WScript.Shell")
   objShell.Run strShutdown

Wscript.Quit

Learning Points

Note 1: This (1a) is the advanced, smooth efficient version.  The next example 1b shows the wart's and all learning progression that I initially went through.

Guy Recommends: The Free IP Address Tracker (IPAT) IP Tracker

Calculating IP Address ranges is a black art, which many network managers solve by creating custom Excel spreadsheets.  IPAT cracks this problem of allocating IP addresses in networks in two ways:

For Mr Organized there is a nifty subnet calculator, you enter the network address and the subnet mask, then IPAT works out the usable addresses and their ranges. 

For Mr Lazy IPAT discovers and then displays the IP addresses of existing computers.  Download the Free IP Address Tracker

Example 1b - The Original Version by Guy Thomas

The first point that I want to make is this, in example 1b, I have deliberately left in a VBScript command that will abort the restart.  When you are ready to test YOUR script, and for real, remove the lines underneath :
'  Abort Shutdown while testing Rem out next x lines in real script

My strongest advice is master the above command FIRST, before you proceed to test shutdown in anger.

See more about shutdown here:

Instructions

  1. Copy and paste the script below into notepad.  Alternatively, use a script editor like VBsEdit.
  2. Save the file with .vbs extension e.g. Shutdown.vbs.
  3. Double click and then enter in the input box, the computername that you wish to shut down.
  4. My VBScript as written, will abort the shutdown, remove the relevant lines when YOU are ready to go live.

' Shutdown.vbs
' Example VBScript to Shutdown computers
' Author Guy Thomas http://computerperformance.co.uk/
' Version 3.3 - September 12th 2004
' --------------------------------------

Option Explicit
Dim objShell, strComputer, strInput, intShort, intLong
Dim strShutdown, strShutdownSwitch, strAbort
' Set the delay for commands in the Dos Box
intShort = 100
intLong =10000 ' Reduce if you wish

' Input Box to get name of machine to shutdown
Do
strComputer = (InputBox(" ComputerName to shutdown", "Computer Name"))
     If strComputer <> "" Then
     strInput = True
     End if
Loop until strInput = True

strShutdown = "shutdown /s /t 60 /m \\" & strComputer
' chr(34) escapes speech marks - so they display in Dos Box
strShutdownSwitch = " /c " & Chr(34) & "Guy Shutdown " & Chr(34) & " /f"
strAbort = "shutdown /a /m \\"
Set objShell = CreateObject("WScript.Shell")
objShell.Run "cmd"
Wscript.Sleep intShort
objShell.SendKeys strShutdown & strShutdownSwitch
Wscript.Sleep intLong
objShell.SendKeys "{ENTER}"

'  Abort Shutdown while testing Rem out next 8 lines in real script
objShell.Run "cmd"
Wscript.Sleep intShort
objShell.SendKeys strAbort & strComputer
Wscript.Sleep intShort
objShell.SendKeys "{ENTER}"
Wscript.Sleep intShort
'  This section closes the Two Dos boxes
Call CloseBox()

Call CloseBox()

'  Sub Routine CloseBox()
Sub CloseBox()
     Wscript.Sleep intLong
     objShell.SendKeys "exit"
     objShell.SendKeys "{ENTER}"
     Wscript.Sleep intShort
End Sub

WScript.Echo "Beware: you tried to shutdown " & strComputer
Wscript.Quit

' End of example Shutdown VBScript

Learning Points

Note 1:  InputBox is the VBScript method which prompts you for the computer name.  This is the name of the machine to shutdown.  In effect InputBox saves having to hardcode strComputer = "BigServer". My basic error checking invokes the 'if' command which in turn, checks for blank names.  Did you like the 'DO ... Loop Until' command?

Note 2:  Sub (routine) is this week's new command.  I have experimented with recycling code.  In particular we need two DOS boxes, therefore we need two commands to quit the DOS box.  Look out for a Sub Function called CloseBox().  You could have used any name, for example, DosExit() would work just as well.  How could you take advantage of SUB CloseBox()?  The answer is that you 'Call' the sub routine, for example: Call CloseBox().  Note:  'Call Sub CloseBox()', would be wrong.

Note 3:  & Chr(34) is used to generate a speech mark sometimes called a double quotes.  I needed this trick to make quotes within quotes work successfully.

Note 4:  You did remember to remove or 'Rem out the abort lines on the real script?

Note 5:  Shutdown /t 60 adds a one minute delay before shutdown.  The /c switch is purely an indulgence which adds a comment.

VBS Shutdown Challenges and Ideas

1) Add a default value to the inputbox.  For example, "LocalHost" or ,"BigServer".

strComputer = (InputBox("Enter ComputerName to shutdown", "Computer Name", "LocalHost"))

2) My script employs the usual range of string and integer variables. Perhaps you would like to reduce the value of intLong from 10 seconds to 3 seconds?  If so, reduce intLong from 10000 to = 3000.

3) Experiment with different values for the /c  "Comment" and /t 60 switches.

4) If you are feeling bolder, why not investigate other shutdown switches, for example /r to restart instead of /s which merely shuts down the machine.

See more about Windows 2003 remote shutdown commands:

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11

SolarWinds' Orion performance monitor will help you discover what's happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds' Network Performance Monitor

Example 2: Script to Shutdown all Computers in a named OU 
Kindly sent in by John Wagner

This is an advanced script which is meant to give you ideas to shutdown a bunch of computers with one script.  In the right hands the end result is satisfying.  In the hands of someone who does not understand all the components, it could cause havoc in their network.

In order to get his script working, you will need to modify some of the values, for example:
LDAP://ou=TestShutdown,ou=computers-managed,dc=your,dc=domain,dc=local

'Script to shutdown computers in an ou in a domain.
'2007-11-27
'John Wagner
'AD hooks from George Padavick
On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

Set objCOmmand.ActiveConnection = objConnection objCommand.CommandText = _
"Select Name, Location from 'LDAP://ou=TestShutdown,ou=computers-managed,dc=your,dc=domain,dc=local' " _
& "Where objectClass='computer'"
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Set objRecordSet = objCommand.Execute objRecordSet.MoveFirst

Do Until objRecordSet.EOF
   'Wscript.Echo "Computer Name: " & objRecordSet.Fields("Name").Value
   'Wscript.Echo "Location: " & objRecordSet.Fields("Location").Value
   txtPCName = objRecordSet.Fields("Name").Value
   txtshutdown = "shutdown -t 180 -s -f -m \\" & txtPCName
   set objShell = CreateObject("WScript.Shell")
   objShell.Run txtShutdown
   objRecordSet.MoveNext
Loop

Learning Points

Note 1:  Of all the scripts that I feature, this is a classic for getting each component working properly in isolation, then assembling the sections to make a production script.

Note 2:  The central belief is that all the computers in a particular OU need shutting down.  Should this not be the case, then consider adding some 'If' statements to ensure that you shutdown only the desired computers.

Note 3: John adds: After further testing you may want to note that the server running the script will need to have rights to the admin$ share and be able to connect thru the firewall.  If most of the computers are off, this script will take about 30 seconds to fail on each.  This may be a concern for large OU's.

Summary of Shutdown

If you want to save that long walk to the server room then consider the built-in shutdown command.  Beware of rebooting the wrong machine!  Take the time to investigate the switches of the shutdown command.  In particular become expert at the abort switch: shutdown /a  /m  \\ machinename.  The sample script has a 'safety catch' which aborts the shutdown, find the lines and remove in your final production VBScript.

 


Custom Search

Site Home

Guy Recommends: WMI Monitor and It's Free!Solarwinds WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.

Fortunately, SolarWinds have created the Free WMI Monitor so that you can actually see and understand these gems of operating system information.  Take the guess work out of which WMI counters to use for scripts.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2014 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: