VBScript: Shut Down Computer If Not Logged On


Scripts & Tools

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

Share It!

This does not work with Win7 64it. From what I can find, MS does not log"full" logon details. Scripts such as this cannot work 100% until MS makes a logging change.

Please reply if there is a fix.

Thanks
also interested if anyone has found a workaround for Win7 x64
I haven't taken a look at the second script yet, but for the first script on my Windows 7 x64 machine I originally received an error of "privilege not held" (after commenting out the the error capture line). I was able to get it to work properly by changing the last section to the following:


OLD:
'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


NEW:
'If no one is logged on shut down the computer
If strLoggedOn = "No" Then
     For each objOperatingSystem in GetObject("winmgmts:{(Shutdown)}!").InstancesOf("Win32_OperatingSystem") 
          objOperatingSystem.Win32Shutdown 1 	
     Next 
End If
Edited on Thursday, January 10 2013 @ 05:31 PM EST by Admin
i tried the script but it doesn't work even i added the user to the wmi root\cimv2 security
i have inserted many msgbox to debug it and only strcomputername show the computer name...the other no msgbox appear...i have tried also the modification for win7 x64 but again it doesn't work.
Please let me know.
Regards.
solved by using the modification of Seker.
ggg
Thanks. After the adjustment from Seker the local version is working here. Unfortunately the PC does reboot if someone is logged on with a remote session (RDP) at the PC. It would be great if someone knows how to work around this also.
I am unprecedented at book inspections furthermore thus I am cautious hardly to do the aggrieve individual. Possibly to relieve me you can recite me how to correspond the superior paper in an upright road. It would be injustice of me to recline about some of these liturgys.
When a post can be mentioned as truly useful, it should be made in a detailed format like this one. You have come across the data quite well and listed the exact things without a miss to make it effective to the readers. I do work for a professional resume writing service where I'm used to help the job candidates with various resume suggestions, hence it brings some more pleasure to have seen this contributing effort from you. Hope to see many more contributions from you of this kind and it truly make the members to be here forever.