Computer Performance, Windows 2003 Vista Best Practice

Best Practice Ezine #97b - ShutdownRestart.wsf

Best Practice Ezine.  Computer Performance. Advertise

<?xml version="1.0" ?>
<package>
<job id="ShutdownRestart" prompt="no">
<?job error="false" debug="false" ?>
<runtime>
<description>
Shutdown or restart one or more computers.

Use only one of the following:
/list:filename : text file containing one computer name per line
/container:ouname : name of an OU containing computer accounts
/computer:name : run command against single specified computer

The following is required:
/action:restart | logoff | shutdown | poweroff

Other arguments are optional.
</description>
<named helpstring="Text file to pull computer names from" name="list" required="false" type="string"/>
<named helpstring="OU to pull computer names from" name="container" required="false" type="string"/>
<named helpstring="Run command against single specified computer" name="computer" required="false" type="string"/>
<named helpstring="Display detailed messages" name="verbose" required="false" type="simple"/>
<named helpstring="Use with /container to include sub-OUs" name="recurse" required="false" type="simple"/>
<named helpstring="File to log names which can't be reached" name="log" required="false" type="string"/>
<named helpstring="Reduce timeout wait by pinging before attempting" name="ping" required="false" type="simple"/>
<named helpstring="Action to take" name="action" required="true" type="string"/>
<named helpstring="Force the specified action" name="force" required="false" type="simple"/>
</runtime>
<object id="fso" progid="Scripting.FileSystemObject"/>
<script id="MultiComputer" language="VBScript">
<![CDATA[
'----------------------------------------------------------
' Shutdown/restart computers
'----------------------------------------------------------

'make sure we're running from CScript, not WScript
If LCase(Right(WScript.FullName,11)) <> "cscript.exe" Then
If MsgBox("This script is designed to work with CScript, but you are running it under WScript. " & _
"This script may produce a large number of dialog boxes when running under WScript, which you may " & _
"find to be inefficient. Do you want to continue anyway?",4+256+32,"Script host warning") = 7 Then
WScript.Echo "Tip: Run ""Cscript //h:cscript"" from a command-line to make CScript the default scripting host."
WScript.Quit
End If
End If

'count arguments
Dim iArgs
If WScript.Arguments.Named.exists("computer") Then iArgs = iArgs + 1
If WScript.Arguments.Named.exists("container") Then iArgs = iArgs + 1
If WScript.Arguments.Named.exists("list") Then iArgs = iArgs + 1
If iArgs <> 1 Then
WScript.Echo "Must specify either /computer, /container, or /list arguments."
WScript.Echo "May not specify more than one of these arguments."
WScript.Echo "Run command again with /? argument for assistance."
WScript.Quit
End If

'if ping requested, make sure we're on XP or later
Dim bPingAvailable, oLocalWMI, cWindows, oWindows
bPingAvailable = False
Set oLocalWMI = GetObject("winmgmts:\\.\root\cimv2")
Set cWindows = oLocalWMI.ExecQuery("Select BuildNumber from Win32_OperatingSystem",,48)
For Each oWindows In cWindows
If oWindows.BuildNumber >= 2600 Then
bPingAvailable = True
End If
Next

'required argument
If not WScript.Arguments.Named.Exists("action") Then
WScript.Echo "Missing required argument /action"
WScript.Arguments.ShowUsage
WScript.Quit
End If

'was ping requested?
If WScript.Arguments.Named.Exists("ping") Then
If bPingAvailable Then
Verbose "will attempt to ping all connections to improve performance"
Else
WScript.Echo "*** /ping not supported prior to Windows XP"
End If
End If

'either /list, /computer, or /container was specified:
Dim sName
If WScript.Arguments.Named("list") <> "" Then
'specified list - read names from file
Dim oFSO, oTS
Verbose "Reading names from file " & WScript.Arguments.Named("list")
Set oFSO = WScript.CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set oTS = oFSO.OpenTextFile(WScript.Arguments.Named("list"))
If Err <> 0 Then
WScript.Echo "Error opening " & WScript.Arguments.Named("list")
WScript.Echo Err.Description
WScript.Quit
End If
Do Until oTS.AtEndOfStream
sName = oTS.ReadLine
TakeAction sName
Loop
oTS.Close

Elseif WScript.Arguments.Named("container") <> "" Then
'specified container - read names from AD
Dim oObject, oRoot, oChild
Verbose "Reading names from AD container " & WScript.Arguments.Named("container")
On Error Resume Next
Set oRoot = GetObject("LDAP://rootDSE")
If Err <> 0 Then
WScript.Echo "Error connecting to default Active Directory domain"
WScript.Echo Err.Description
WScript.Quit
End If
Set oObject = GetObject("LDAP://ou=" & WScript.Arguments.Named("container") & _
"," & oRoot.Get("defaultNamingContext"))
If Err <> 0 Then
WScript.Echo "Error opening organizational unit " & WScript.Arguments.Named("container")
WScript.Echo Err.Description
WScript.Quit
End If
WorkWithOU oObject

Elseif WScript.Arguments.Named("computer") <> "" Then
'specified single computer
Verbose "Running command against " & WScript.Arguments.Named("computer")
TakeAction WScript.Arguments.Named("computer")

End If

'display output so user will know script finished
WScript.Echo "Command completed."

' ----------------------------------------------------------------------
' Sub WorkWithOU
'
' Iterates child objects in OU; calls itself to handle sub-OUs If
' /recurse argument supplied
' ----------------------------------------------------------------------
Sub WorkWithOU(oObject)
For Each oChild In oObject
Select Case oChild.Class
Case "computer"
TakeAction Right(oChild.Name,len(oChild.name)-3)
Case "user"
Case "organizationalUnit"
If WScript.Arguments.Named.Exists("recurse") Then
'recursing sub-OU
Verbose "Working In " & oChild.Name
WorkWithOU oChild
End If
End Select
Next
End Sub

' ----------------------------------------------------------------------
' Sub TakeAction
'
' Makes connection and performs command-specific code
' ----------------------------------------------------------------------
Sub TakeAction(sName)

'verbose output?
Verbose "Connecting to " & sName

'ping before connecting?
If WScript.Arguments.Named.Exists("ping") Then
If Not TestPing(sName,bPingAvailable) Then
LogBadConnect(sName)
Exit Sub
End If
End If


'#############################################
'# COMMAND CODE GOES HERE #
'#-------------------------------------------#
'# #

Dim cSystems, oSystem, iAction
Select Case lcase(WScript.Arguments.Named("action"))
Case "shutdown"
iAction = 1
Case "restart"
iAction = 2
Case "logoff"
iAction = 0
Case "poweroff"
iAction = 8
Case Else
WScript.Echo "*** Unknown action " & WScript.Arguments.Named("action")
End Select
If WScript.Arguments.Named.Exists("force") Then
iAction = iAction + 4
End If
Verbose " Connecting to WMI on " & sName
Set cSystems = QueryWMI(sName,"root\cimv2","Select * From Win32_OperatingSystem","","")
If Not IsObject(cSystems) Then
WScript.Echo " *** Couldn't connect to WMI on " & sName
Else
For Each oSystem In cSystems
On Error Resume Next
oSystem.Win32Shutdown(iAction)
If Err <> 0 Then
WScript.Echo " *** Couldn't perform action on " & sName
WScript.Echo " " & Err.Description
Else
Verbose "Successful on " & sName
End If
Next
End If

'# #
'#-------------------------------------------#
'# END COMMAND CODE #
'#############################################

End Sub

' ----------------------------------------------------------------------
' Sub LogBadConnect
'
' Logs failed connections to a log file. Will append if file already exists.
' ----------------------------------------------------------------------
Sub LogBadConnect(sName)
If WScript.arguments.Named.Exists("log") Then
Dim oLogFSO, oLogFile
Set oLogFSO = WScript.CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set oLogFile = oLogFSO.OpenTextFile(WScript.Arguments.Named("log"),8,True)
If Err <> 0 Then
WScript.Echo " *** Error opening log file to log an unreachable computer"
WScript.Echo " " & Err.Description
Else
oLogFile.WriteLine sName
oLogFile.Close
Verbose " Logging " & sName & " as unreachable"
End If
End If
End Sub


' ----------------------------------------------------------------------
' Function TestPing
'
' Tests connectivity to a given name or address; returns true or False
' ----------------------------------------------------------------------
Function TestPing(sName,bPingAvailable)
If Not bPingAvailable Then
WScript.Echo " Ping functionality not available prior to Windows XP"
Exit Function
End If
Dim cPingResults, oPingResult
Verbose " Pinging " & sName
Set cPingResults = GetObject("winmgmts://./root/cimv2").ExecQuery("SELECT * FROM Win32_PingStatus WHERE Address = '" & sName & "'")
For Each oPingResult In cPingResults
If oPingResult.StatusCode = 0 Then
TestPing = True
Verbose " Success"
Else
TestPing = False
Verbose " *** FAILED"
End If
Next
End Function

' ----------------------------------------------------------------------
' Sub Verbose
'
' Outputs status messages if /verbose argument supplied
' ----------------------------------------------------------------------
Sub Verbose(sMessage)
If WScript.Arguments.Named.Exists("verbose") Then
WScript.Echo sMessage
End If
End Sub

' ----------------------------------------------------------------------
' Sub LogFile
'
' Outputs specified text to specified logfile. Set Overwrite=True To
' overwrite existing file, otherwise file will be appended to.
' Each call to this sub is a fresh look at the file, so don't Set
' Overwrite=True except at the beginning of your script.
' ----------------------------------------------------------------------
Sub LogFile(sFile,sText,bOverwrite)
Dim oFSOOut,oTSOUt,iFlag
If bOverwrite Then
iFlag = 2
Else
iFlag = 8
End If
Set oFSOOut = WScript.CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set oTSOUt = oFSOOut.OpenTextFile(sFile,iFlag,True)
If Err <> 0 Then
WScript.Echo "*** Error logging to " & sFile
WScript.Echo " " & Err.Description
Else
oTSOUt.WriteLine sText
oTSOUt.Close
End If
End Sub

' ----------------------------------------------------------------------
' Function QueryWMI
'
' Executes WMI query and returns results. User and Password may be
' passed as empty strings to use current credentials; pass just a blank
' username to prompt for the password
' ----------------------------------------------------------------------
Function QueryWMI(sName,sNamespace,sQuery,sUser,sPassword)
Dim oWMILocator, oWMIService, cInstances
On Error Resume Next

'create locator
Set oWMILocator = CreateObject("WbemScripting.SWbemLocator")

If sUser = "" Then

'no user - connect w/current credentials
Set oWMIService = oWMILocator.ConnectServer(sName,sNamespace)
If Err <> 0 Then
WScript.Echo "*** Error connecting to WMI on " & sName
WScript.Echo " " & Err.Description
Set QueryWMI = Nothing
Exit Function
End If

Else

'user specified
If sUser <> "" And sPassword = "" Then

'no password - need to prompt for password
If LCase(Right(WScript.FullName,11)) = "cscript.exe" Then

'cscript - attempt to use ScriptPW.Password object
Dim oPassword
Set oPassword = WScript.CreateObject("ScriptPW.Password")
If Err <> 0 Then
WScript.Echo " *** Cannot prompt for password prior to Windows XP"
WScript.Echo " Either ScriptPW.Password object not present on system, Or"
WScript.Echo " " & Err.Description
WScript.Echo " Will try to proceed with blank password"
Else
WScript.Echo "Enter password for user '" & sUser & "' on '" & sName & "'."
sPassword = oPassword.GetPassword()
End If
Else

'wscript - prompt with InputBox()
sPassword = InputBox("Enter password for user '" & sUser & "' on '" & sName & "'." & vbcrlf & vbcrlf & _
"WARNING: Password will echo to the screen. Run command with CScript to avoid this.")
End if
End If

'try to connect using credentials provided
Set oWMIService = oWMILocator.ConnectServer(sName,sNamespace,sUser,sPassword)
If Err <> 0 Then
WScript.Echo " *** Error connecting to WMI on " & sName
WScript.Echo " " & Err.Description
Set QueryWMI = Nothing
Exit Function
End If
End If

'execute query
If sQuery <> "" Then
Set cInstances = oWMIService.ExecQuery(sQuery,,48)
If Err <> 0 Then
WScript.Echo "*** Error executing query "
WScript.Echo " " & sQuery
WScript.Echo " " & Err.Description
Set QueryWMI = Nothing
Exit Function
Else
Set QueryWMI = cInstances
End If
Else
Set QueryWMI = oWMIService
End If

End Function

' ----------------------------------------------------------------------
' Function QueryADSI
'
' Executes ADSI query. Expects variable sQuery to include a COMPLETE
' query beginning with the provider LDAP:// or WinNT://. The query String
' may include a placeholder for the computer name, such as "%computer%".
' Include the placeholder in variable sPlaceholder to have it replaced
' with the current computer name. E.g.,
' sQuery = "WinNT://%computer%/Administrator,user"
' sPlaceholder = "%computer%
' Will query each computer targeted by the script and query their local
' Administrator user accounts.
' ----------------------------------------------------------------------
Function QueryADSI(sName,sQuery,sPlaceholder)

Dim oObject
sQuery = Replace(sQuery,sPlaceholder,sName)
On Error Resume Next
Verbose " Querying " & sQuery
Set oObject = GetObject(sQuery)
If Err <> 0 Then
WScript.Echo " *** Error executing ADSI query"
WScript.Echo " " & sQuery
WScript.Echo " " & Err.Description
Set QueryADSI = Nothing
Else
Set QueryADSI = oObject
End If

End Function
]]>
</script>
</job>
</package>
 

Cisco

Have you noticed how rock stars are in fact frustrated sportsmen, while sportsmen all want to be rock stars?  Even within sportsmen all runners really want to be footballers.  I find there is a similar effect in computing, here am I a minor expert in Windows who would love to explore Cisco.  If you too would like to learn Cisco why not start with TrainSignal's videos and associated learning material.

 

 *


Google

Web  This website

Review of Orion NPMGuy Recommends: Orion's NPM - Network Performance Monitor

Orion's performance monitor is designed for detecting network outages. A network-centric view make it easy to see what's working, and what needs your attention.

This utility guides you through troubleshooting by indicating whether the root cause is faulty equipment or resource overload.

Download a free trial of the Network Performance Monitor

 

Home Copyright © 1999-2010 Computer Performance LTD All rights reserved

Please report a broken link, or an error.