Stop and Start Windows Services Script

Joined
Dec 9, 2003
Messages
4,905
Location
Decorah, IA
Car(s)
2004 Subaru Impreza WRX STI (USDM)
I wrote a script that I've been meaning to write for quite some time but hadn't got around to until now.

What it does:
It stops all Windows services that are running except for ones listed in an exclude file.
It also sets the start up mode to manual for any that are set to automatic.

This could be useful for gaming if you're worried about certain services accessing resources such as the network, the disk, etc... while you're playing.

What it does not do:
It doesn't stop any "normal" processes (programs that aren't services), you still have to close those manually.
It doesn't force any service to stop that it can't using the normal API routines (it doesn't use brute force).
This means it is possible that services that potentially interfere (like Task Scheduler) could still be left running.

How to "install" it:
  1. Download the AllServices.vbs and AllServicesExclude.csv and put them anywhere you like (as long as they're together).
  2. Create a shortcut to the AllServices.vbs file and place it on the Desktop (or anywhere else you would like to).
  3. Edit the shortcut, and put the text "cscript " (without the quotes, but with the space) in front of the Target field.
    When you close and re-edit the shortcut, the Target field should look something like this:
    C:\Windows\System32\cscript.exe C:\Games\AllServices.vbs
  4. Rename the shortcut to "Stop Services". (or anything else you'd like).
  5. Make a copy of this shortcut, and rename it to "Start Services".
  6. Edit the "Start Services" shortcut, and put the text " Start" (without the quotes, but with the space) at the end of the Target field.
    When you close and re-edit the shortcut, the Target field should look something like this:
    C:\Windows\System32\cscript.exe C:\Games\AllServices.vbs Start
  7. Edit the AllServicesExclude.csv file so that it lists all the services that you do not want to be stopped.
  8. Create a restore point.
How to use it:
  1. Manually stop any programs that you don't need during gaming.
  2. Run the "Stop Services" shortcut.
  3. Go start your game and play.
  4. When done run the "Start Services" shortcut.
  5. Start any programs closed in step 1 if needed.
Notes / warnings:
  • Since this script changes auto start services to manual start, you should run the start script again before shutting down.
    If you forget, Windows might not have such a fun time during start up.
  • Before you run it the first time, it's probably a good idea to create a restore point.
  • The first time you run it, it will create a file with the list of services and their current state (AllServicesOriginal.csv), this is purely for safe keeping.
  • I only tested this on my own Vista Ultimate machine, I haven't yet tried in on my Windows XP box.
  • If your PC bursts in to flames, it's not my fault, don't blame me.
    However if something bad does happen, one of these steps should fix it:
  • Run the "Start Services" again.
  • Look at the AllServicesOriginal.csv file and manually change the services to reflect that state.
  • Go back the the restore point.
Download:
http://espnsti.iridiumonline.info/LFS/Tools/AllServices/AllServices.rar
If the download doesn't work (which it doesn't appear to at the moment), then just copy and paste the source below in to text files.

Source:

AllServices.vbs:
Code:
'
' AllServices.vbs
'
' This script will either stop all services except for the ones listed in the exclude file.
' Or it will start all the services listed in the start services file
'
'
' Syntax (optional parameters listed in parentheses):
'
' CScript AllServices.vbs [Stop] [<Exclude File>] [<Running Services Output File>]
'
' <Exclude File> =  A text file containing a list of services that you do not want stopped.
'                   The default for this parameter is "AllServicesExclude.csv".  
' <Running Services Output File> = A text file that will contain a list of services that
'                   were running at the time this script is ran.
'                   The default for this parameter is "AllServicesSaved.csv".  
'
' or
'
' CScript AllServices.vbs Start <Services File>
' <Services File> = A text file containing a list of services that you want started.
'                   The default for this parameter is "AllServicesSaved.csv".
'

Dim objFSO
Dim objWMIService
Dim objDictStartStopError
Dim objDictExclude
Dim objDictStartStop
Dim objFileStoppedServices
Dim objDictArgs

Init
Main

' -----------------------------------------------------------------------------------

Sub Main
    ' Preserve a copy of the services as they were the first time this script was ran
    If Not objFSO.FileExists("AllServicesOriginal.csv") Then
        WriteServicesFile "AllServicesOriginal.csv", False
    End If

    If LCase(objDictArgs("Command")) = "stop" Then StopServices
    If LCase(objDictArgs("Command")) = "start" Then StartServices
End Sub

' -----------------------------------------------------------------------------------

Sub StopServices
    ' Assume that if the file exists that the stop script is being run a second time and
    ' we don't want to save the current state.
    If Not objFSO.FileExists("AllServicesInStopMode.txt") Then
        ' Save the current list of services and their state
        WriteServicesFile objDictArgs("StartFile"), True

        ' Put us in to stop mode
        objFSO.CreateTextFile("AllServicesInStopMode.txt")
    End If
  
    Do
        SomeSucceeded = False
        ' Loop through all services that are running and can be stopped 
        ' or are set to auto start.
        Set colServices = objWMIService.ExecQuery _
            ("Select * from Win32_Service Where (Started = True And AcceptStop = True) " _
            & " Or StartMode = 'Auto'")
        For Each objService in colServices
            If StopService(objService) Then SomeSucceeded = True
        Next

        'Repeat while we were able to stop some services
    Loop While SomeSucceeded
End Sub

' -----------------------------------------------------------------------------------

Function StopService(objService)
    StopService = False

    ' Can't stop the Windows Management Instrumentation service since this script
    ' is using it.
    If LCase(objService.Name) = "winmgmt" Then 
        Exit Function
    End If
   
    ' Skip any service that is in the exclude list.
    If objDictExclude.Exists(LCase(objService.Name)) _
            Or objDictExclude.Exists(LCase(objService.DisplayName)) Then
        Exit Function
    End If

    ' Change the start mode from "Auto" to "Manual" if needed
    If Not objService.Started Or Not objService.AcceptStop Then
        If objService.StartMode = "Auto" Then
            Wscript.Echo "Stopping: " & objService.DisplayName & " (" & objService.Name & ")"
            errReturnCode = objService.ChangeStartMode("Manual")
            If errReturnCode <> 0 Then
                Wscript.Echo "    error: " & objDictStartStopError.Item(errReturnCode)
            End If
        End If
        Exit Function
    End If 

    ' Don't try to stop it if it isn't allowed
    If objService.AcceptStop = False Then 
        Exit Function
    End If

    StopService = True

    ' Stop dependent services
    Set colDependentServices = objWMIService.ExecQuery("Associators of " _
        & "{Win32_Service.Name='" & objService.Name & "'} Where " _
        & "AssocClass=Win32_DependentService " & "Role=Antecedent " )
    For each objDependentService in colDependentServices
        If Not StopService(objDependentService) Then
            StopService = False
        End If
    Next

    ' Change the start mode from "Auto" to "Manual" if needed
    Wscript.Echo "Stopping: " & objService.DisplayName & " (" & objService.Name & ")"
    If objService.StartMode = "Auto" Then
        errReturnCode = objService.ChangeStartMode("Manual")
        If errReturnCode <> 0 Then
            Wscript.Echo "    error: " & objDictStartStopError.Item(errReturnCode)
        End If
    End If

    ' Stop the service
    errReturnCode = objService.StopService()   
    If errReturnCode = 0 Then
        ' Wait for it to finish stopping
        Do 
            StillRunning = False
            Wscript.Sleep 100
            Set colCurrentServices = objWMIService.ExecQuery _
                ("Select * from Win32_Service Where Name = '" & objService.Name & "'")
            For Each objCurrentService in colCurrentServices
                If objCurrentService.State <> "Stopped" Then StillRunning = True
            Next
        Loop While StillRunning
    Else 
        If errReturnCode <> 10 Then
            ' Report the error
            Wscript.Echo "    error: " & objDictStartStopError.Item(errReturnCode)
        
            'Check to make sure it didn't stop
            Wscript.Sleep 100
            Set colCurrentServices = objWMIService.ExecQuery _
                ("Select * from Win32_Service Where Name = '" & objService.Name & "'")
            For Each objCurrentService in colCurrentServices
                If objCurrentService.State <> "Stopped" Then StillRunning = True
            Next
            StopService = Not StillRunning
        End If
    End If 
End Function

' -----------------------------------------------------------------------------------

Sub StartServices
    If objFSO.FileExists(objDictArgs("StartFile")) Then
        ' Read the services file
        Set objDictStartStop = CreateObject("Scripting.Dictionary")
        ReadServicesFile objDictArgs("StartFile"), objDictStartStop

        Do
            SomeFailed = False
            SomeSucceeded = False
            For Each Service In objDictStartStop.Keys
                If StartService(Service, objDictStartStop(Service)(1), _
                        objDictStartStop(Service)(2)) Then 
                    SomeSucceeded = True
                Else
                    SomeFailed = True
                End If
            Next

            'Repeat while we were able to start some services
        Loop While SomeSucceeded And SomeFailed

        ' We're out of stop mode
        If objFSO.FileExists("AllServicesInStopMode.txt") Then
            objFSO.DeleteFile("AllServicesInStopMode.txt")
        End If
    End If
End Sub

' -----------------------------------------------------------------------------------

Function StartService(Service, StartMode, Started)
    StartService = True

    If LCase(Started) = "started" Then
        ' Attempt to start the dependent services by name
        Set colServiceList = objWMIService.ExecQuery("Associators of " _
            & "{Win32_Service.Name='" & Service & "'} Where " _
            & "AssocClass=Win32_DependentService " & "Role=Dependent" )
On Error RESUME NEXT
        For each objService in colServiceList
            If Not objService.Started Then 
                If Not StartSerivce(objService.Name, objService.StartMode, "started") Then StartService = False
            End If 
        Next
On Error GOTO 0

        ' Attempt to start the dependent services by display name
        Set colServiceList = objWMIService.ExecQuery("Associators of " _
            & "{Win32_Service.DisplayName='" & Service & "'} Where " _
            & "AssocClass=Win32_DependentService " & "Role=Dependent" )
On Error RESUME NEXT
        For each objService in colServiceList
            If Not objService.Started Then 
                If Not StartSerivce(objService.Name, objService.StartMode, "started") Then StartService = False
            End If
        Next
On Error GOTO 0
    End If

    FoundService = False
    ' Get the service object
    Set colServiceList = objWMIService.ExecQuery _
        ("Select * from Win32_Service where Name='" & Service & "'" _
             & " Or DisplayName = '" & Service & "'")
    For each objService in colServiceList
        FoundService = False

        ' Change the service start mode from "Manual" back to "Auto" if needed.
        EchoedStarting = False
        If (LCase(StartMode) = "auto") And (LCase(objService.StartMode) = "manual") Then
            Wscript.Echo "Starting: " & objService.DisplayName & " (" & objService.Name & ")"
            EchoedStarting = True
            errReturnCode = objService.ChangeStartMode("Automatic")
            If errReturnCode <> 0 Then
                StartService = False
                Wscript.Echo "    error: " & objDictStartStopError.Item(errReturnCode)
            End If
        End If

        ' Start the service if needed
        If Not objService.Started And (LCase(Started) = "started") Then
            If Not EchoedStarting Then
                Wscript.Echo "Starting: " & objService.DisplayName & " (" & objService.Name & ")"
                EchoedStarting = True
            End If

            ' Start the service
            errReturnCode = objService.StartService()  
            If errReturnCode = 0 Then
                ' Wait for it to complete starting
                Do 
                    StillStopped = False
                    Wscript.Sleep 100
                    Set colCurrentServices = objWMIService.ExecQuery _
                        ("Select * from Win32_Service Where Name = '" & objService.Name & "'")
                    For Each objCurrentService in colCurrentServices
                        If objCurrentService.State <> "Running" Then StillStopped = True
                    Next
                Loop While StillStopped
            Else 
                ' Report the error
                If errReturnCode <> 10 Then
                    Wscript.Echo "    error: " & objDictStartStopError.Item(errReturnCode)

                    'Check to make sure it didn't start
                    StillStopped = False
                    Wscript.Sleep 100
                    Set colCurrentServices = objWMIService.ExecQuery _
                        ("Select * from Win32_Service Where Name = '" & objService.Name & "'")
                    For Each objCurrentService in colCurrentServices
                        If objCurrentService.State <> "Running" Then StillStopped = True
                    Next
                    StartService = Not StillStopped 
                End If
            End If
        End If

    Next
    If Not FoundService Then StartService = False
End Function

' -----------------------------------------------------------------------------------

Sub ReadServicesFile(FileName, objServicesDictionary)
    If objFSO.FileExists(FileName) Then
        ' Open the file
        Set objTextFile = objFSO.OpenTextFile(FileName, 1)
        Do Until objTextFile.AtEndOfStream
            ' Split the line in to an array
            aService = Split(objTextFile.Readline, ",")
            If UBound(aService) < 2 Then Redim Preserve aService(2)
            ' Lower case and time it
            aService(0) = LCase(Trim(aService(0))) ' Service Name
            aService(1) = LCase(Trim(aService(1))) ' Start Mode
            aService(2) = LCase(Trim(aService(2))) ' "Started" indicator
            objServicesDictionary.Add aService(0), aService
        Loop
        objTextFile.Close
    End If
End Sub

' -----------------------------------------------------------------------------------

Sub WriteServicesFile(FileName, UseExclude)
    ' Create the record set structure
    Const adVarChar = 200
    Const MaxCharacters = 255
    Set DataList = CreateObject("ADOR.Recordset")
    DataList.Fields.Append "DisplayName", adVarChar, MaxCharacters
    DataList.Fields.Append "StartMode", adVarChar, MaxCharacters
    DataList.Fields.Append "Started", adVarChar, MaxCharacters
    DataList.Open

    ' Get a list of all services
    Set colServices = objWMIService.ExecQuery("Select * from Win32_Service")
    For Each objService in colServices   
        ' Skip excluded services if needed
        If Not UseExclude Or (Not objDictExclude.Exists(LCase(objService.Name)) _
                And Not objDictExclude.Exists(LCase(objService.DisplayName))) Then
            ' Copy settings in to the record set.
            DataList.AddNew
            DataList("DisplayName") = objService.DisplayName
            DataList("StartMode") = objService.StartMode
            If objService.Started Then 
                DataList("Started") = "Started"
            Else
                DataList("Started") = ""
            End If
            DataList.Update
        End If
    Next

    ' Create the text file
    Set objTextFile = objFSO.CreateTextFile(FileName, True)    

    ' Loop through the record set
    DataList.Sort = "DisplayName"
    DataList.MoveFirst
    Do Until DataList.EOF
        ' Write to the file
        Line = DataList.Fields.Item("DisplayName") & ", " _ 
            & DataList.Fields.Item("StartMode")
        If DataList.Fields.Item("Started") <> "" Then 
            Line = Line & ", " & DataList.Fields.Item("Started")
        End If
        objTextFile.WriteLine Line
        DataList.MoveNext
    Loop
    objTextFile.Close
End Sub

' -----------------------------------------------------------------------------------

Sub Init
    Set objDictArgs = CreateObject("Scripting.Dictionary")
    For i = 0 to Wscript.Arguments.Count - 1
      If i = 0 Then objDictArgs.Add "Command", Wscript.Arguments(i)    
      If LCase(objDictArgs("Command")) = "stop" Then
          If i = 1 Then objDictArgs.Add "ExcludeFile", Wscript.Arguments(i)
          If i = 2 Then objDictArgs.Add "StartFile", Wscript.Arguments(i)
      End If 
      If LCase(objDictArgs("Command")) = "start" Then
          If i = 1 Then objDictArgs.Add "StartFile", Wscript.Arguments(i)
      End If
    Next
    If objDictArgs("Command") = "" Then
        objDictArgs.Remove "Command"
        objDictArgs.Add "Command", "Stop"
    ENd If
    If objDictArgs("ExcludeFile") = "" Then 
        objDictArgs.Remove "ExcludeFile"
        objDictArgs.Add "ExcludeFile", "AllServicesExclude.csv"
    ENd If
    If objDictArgs("StartFile") = "" Then 
        objDictArgs.Remove "StartFile"
        objDictArgs.Add "StartFile", "AllServicesSaved.csv"
    ENd If

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    strComputer = "."
    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

    Set objDictStartStopError = CreateObject("Scripting.Dictionary")
    objDictStartStopError.Add 0,     "Success."
    objDictStartStopError.Add 1,     "Not supported."
    objDictStartStopError.Add 2,     "Access denied."
    objDictStartStopError.Add 3,     "Dependent services running."
    objDictStartStopError.Add 4,     "Invalid service control."
    objDictStartStopError.Add 5,     "Service cannot accept control."
    objDictStartStopError.Add 6,     "Service not active."
    objDictStartStopError.Add 7,     "Service request timeout."
    objDictStartStopError.Add 8,     "Unknown failure."
    objDictStartStopError.Add 9,     "Path not found."
    objDictStartStopError.Add 10,    "Service already stopped/running."
    objDictStartStopError.Add 11,    "Service database locked."
    objDictStartStopError.Add 12,    "Service dependency deleted."
    objDictStartStopError.Add 13,    "Service dependency failure."
    objDictStartStopError.Add 14,    "Service disabled."
    objDictStartStopError.Add 15,    "Service logon failed."
    objDictStartStopError.Add 16,    "Service marked for deletion."
    objDictStartStopError.Add 17,    "Service no thread."
    objDictStartStopError.Add 18,    "Status circular dependency."
    objDictStartStopError.Add 19,    "Status duplicate name."
    objDictStartStopError.Add 20,    "Status - invalid name."
    objDictStartStopError.Add 21,    "Status - invalid parameter."
    objDictStartStopError.Add 22,    "Status - invalid service account."
    objDictStartStopError.Add 23,    "Status - service exists."
    objDictStartStopError.Add 24,    "Service already paused."

    Set objDictExclude = CreateObject("Scripting.Dictionary")
    ReadServicesFile objDictArgs("ExcludeFile"), objDictExclude
End Sub
AllServicesExclude.csv:
Code:
DCOM Server Process Launcher
Desktop Window Manager Session Manager
DHCP Client
DNS Client
Human Interface Device Access
Multimedia Class Scheduler
Network Store Interface Service
Plug and Play
Remote Procedure Call (RPC)
User Profile Service
Themes
Windows Audio
Windows Audio Endpoint Builder
Windows Driver Foundation - User-mode Driver Framework
 
Last edited:
Nice one ESPN! :)

Luckily I don't have issues in this area. Before a proper LFS race, I turn off manually the two things that interfere with gaming, antivirus and messenger. However I can see this being quite useful to people running a lot of stuff and that experience often gaming interruption.
 
Yeah, my PC is enough to where nothing interferes with games. :)

Sweet script though. :cool:
 
Hmmmm, wonder if this could solve some of my problems with playing on my desktop :think:
 
Nice one ESPN! :)

Luckily I don't have issues in this area. Before a proper LFS race, I turn off manually the two things that interfere with gaming, antivirus and messenger. However I can see this being quite useful to people running a lot of stuff and that experience often gaming interruption.

I had some framedrops also, and it was antivirus program who was updating :mad: I configured it at a fixed time, a time when i'm not racing ;)
An other problem when i got Outlook running. When it was checked for new mail the internet connection was lagging.
 
Top