How to change the Service account and restart the Service using WMI.

Often we required the service account to be changed and this requires a restart of the service for the change to come in to effect.

Below is a vbscript that uses WMI to achieve this. This script has not been tested on Services that depend on other services. Will update this once those tests are complete.

Note: This is not recommended for Sql server service. In order to change the service account for sql server we can use sql server configuration manager

 

Dim ChangeActStr

Dim Switch

‘You can use other parameters of SC.EXE in the below string like password etc

ChangeActStr="sc config ""<Custom Service Name>"" obj= ""LOCALSYSTEM"""

Set shell = CreateObject("wscript.shell")

Shell.run ChangeActStr,true

Switch=2

While Switch<>1

Set objCollection = GetObject("WinMgmts:").ExecQuery ("Select * from Win32_Service where name='<custom service name>'")

‘Exit if the Service does not exist

If objCollection.count = 0 Then

Wscript.Quit

End if

‘Using the for loop since you can use the same code if you modify the select query above for multiple services.

‘In our case we will have only one row returned

For Each obj in objCollection

                If UCASE(obj.State) <> "STOPPED" Then

                                obj.StopService

                                Wscript.Sleep 2000

                                Set ObjCollection = Nothing

                                Switch=2

                ElseIf UCASE(obj.State) ="STOPPED" Then

                                obj.StartService

                                Wscript.Sleep 2000

                                Switch=1

                End If

Next

Wend

 

 

Levi Justus
Technical Lead, Microsoft Sql Server