VBScript: Shut Down Computer If Not Logged On

Here are a couple VBScripts that you can use to shut down computers if no one is logged on at the time the script is run. This is useful if you want to make sure computers are shut down at the end of the day, but don't want to shut them down if someone is logged in and working. The difference between the two scripts is that one would be run on the local machine(s) that you want to shut down, while the second script can be run from one computer and will attempt to shut down all computers in a specified Organizational Unit (OU). You can use the Task Scheduler to run either of these scripts at a specific time of the day or week.

Obviously, you could also cut out the parts that test to see if someone is logged on if you don't want or need that check

Both of these scripts use the Windows Management Instrumentation (WMI) service and should work on any version of Microsoft Windows from Windows 2000 up and possibly Windows NT, Windows 95, & Windows 98 with the WMI CORE 1.5 distributable.

 

Continue on for the VBS code...

Change the flag value in the Win32Shutdown method to perform a different command
(Source: Win32Shutdown Method of the Win32_OperatingSystem Class)

Value Meaning
0 (0x0) Log Off
4 (0x4) Forced Log Off (0 + 4)
1 (0x1) Shutdown
5 (0x5) Forced Shutdown (1 + 4)
2 (0x2) Reboot
6 (0x6) Forced Reboot (2 + 4)
8 (0x8) Power Off
12 (0xC) Forced Power Off (8 + 4)

Shut Down If Not Logged On - Run Directly On Machine

'*  Script Name:   ShutDownIfNotLoggedOn - Local.vbs
'*  Created On:    12/13/2007
'*  Author:        Michael C. Panagos
'*  Website:       http://www.grimadmin.com
'*  Purpose:       Script to get current user logged on and perform shutdown on computer if no one is logged on
'*  History:       Michael C. Panagos 12/13/2007
'*                 Initial Draft.
'*  Legal:         Copying and distribution of this code, with or without modification,
'*                 are permitted in any medium without royalty provided the copyright
'*                 notice and this notice are preserved.  This code is offered as-is,
'*                 without any warranty.

'Account used to run script needs WMI permissions to shut down computer.


'Set error capture
On Error Resume Next

'Get local computer name
Set wshNetwork = WScript.CreateObject( "WScript.Network" )
strComputerName = wshNetwork.ComputerName
'strComputerName = "ComputerABC" 'For testing specific computer

'Setup WMI calling for logon name and shutdown assignment
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputerName & "\root\cimv2")

'Get currently logged on user's username
Set colComputer = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")
For Each objComputer in colComputer
    If IsNull(objComputer.UserName) Then 'If no one is logged on
        strLoggedOn = "No"
    Else
        strLoggedOn = "Yes"
    End If
Next

'If no one is logged on shut down the computer
If strLoggedOn = "No" Then
    Set colComputer = objWMIService.ExecQuery _
        ("Select * from Win32_OperatingSystem")
    For Each objComputer in colComputer
        objComputer.Win32Shutdown(1)
    Next
End If

Shut Down If Not Logged On - Run From Remote Machine

We've kept some testing lines in the network version of the code to assist with troubleshootingWhen using the network version of the script, make sure DNS is working properly and no personal firewalls are blocking remote WMI access

'*  Script Name:   ShutDownIfNotLoggedOn - Network.vbs
'*  Created On:    12/13/2007
'*  Author:        Michael C. Panagos
'*  Website:       http://www.grimadmin.com
'*  Purpose:       Script to shut down remote computers in specified Active Directory (AD) Organizational Unit (OU) if no one is logged on
'*  History:       Michael C. Panagos 12/13/2007
'*                 Initial Draft.
'*  Legal:         Copying and distribution of this code, with or without modification,
'*                 are permitted in any medium without royalty provided the copyright
'*                 notice and this notice are preserved.  This code is offered as-is,
'*                 without any warranty.

'Account used to run script needs WMI permissions to shut down computer.
'Some code used and modified from 'Hey, Scripting Guy!' series article -> http://www.microsoft.com/technet/scriptcenter/resources/qanda/jan05/hey0121.mspx

'Set variables
strOUtoBrowse = "LDAP://ou=Business,ou=Workstations,dc=XYZCO,dc=com"
'===================================================================


'Set error capture
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.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

objCommand.CommandText = "SELECT Name FROM '" & strOUtoBrowse & "' WHERE objectCategory='computer'"
Set objRecordSet = objCommand.Execute

objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    'wscript.Echo objRecordSet.Fields("Name").Value 'Testing line
    strComputerName = objRecordSet.Fields("Name").Value

    'Check to see if computer is on by pinging it
    Set objShell = CreateObject("WScript.Shell")
    Set objExec = objShell.Exec("ping -n 2 -w 100 " & strComputerName)
    strPingResults = LCase(objExec.StdOut.ReadAll)
    If InStr(strPingResults, "reply from") Then 'If computer responds to echo request

        'Connect to WMI service on remote computer for logon name and shutdown assignment
        Set objWMIService = GetObject("winmgmts:" _
            & "{impersonationLevel=impersonate}!\\" & strComputerName & "\root\cimv2")
        If Err.Number = 0 Then 'If the computer is online
            'wscript.echo "Computer is online" 'Testing line
            'wscript Err.Description 'Testing line
       
            'Get currently logged on user's username to see if someone is logged on
            Set colComputer = objWMIService.ExecQuery _
                ("Select * from Win32_ComputerSystem")
            For Each objComputer in colComputer
                If IsNull(objComputer.UserName) Then 'If no one is logged on
                    strLoggedOn = "No"
                    'wscript.echo "No one is logged on to: " & strComputerName 'Testing line
                Else
                    strLoggedOn = "Yes"
                    'wscript.echo objComputer.UserName & " is logged on to: " & strComputerName 'Testing line
                End If
            Next
       
            'If no one is logged on shut down the computer
            If strLoggedOn = "No" Then
                Set colComputer = objWMIService.ExecQuery _
                    ("Select * from Win32_OperatingSystem")
                For Each objComputer in colComputer
                    objComputer.Win32Shutdown(1)
                Next
            End If
        Else
            'wscript.echo "Computer is offline" 'Testing line
        End If

    End If
    objRecordSet.MoveNext

Loop

 

Tag: vbscript microsoft windows

Comments (9)


The Grim Admin
https://www.grimadmin.com/article.php/vbs-shut-down-computer-if-not-logged-on