Link to home
Start Free TrialLog in
Avatar of rorybrady
rorybrady

asked on

Script to enable and disable service on computers in a domain

Does any one have a script that will enable/disable, start/stop services on all the desktops in a domain?
Avatar of Pber
Pber
Flag of Canada image

Why not just use group policy.  It will disable services and stop them and you can also control the security on the service as well:

See this:
http://www.windowsecurity.com/articles/Controlling-Server-Service-Security-Group-Policy.html

Just create a domain GPO and assign it to the OU that contains computers then configure the target service:

Computer Configuration\Windows Settings\Security Settings\System Services

from there, select the service, set the startup as desired and set security if needed.
Avatar of rorybrady
rorybrady

ASKER

That is a good idea, I think I still need the script to start and stop a service. Correct me if I am wrong but if I set a a service do be disabled through group policy the service won't actually shutdown until after a reboot. Lots of the computers on the domain don't get rebooted for months. That is why I need to get a script for stating and stoping services, I cannot wait until all machines have been rebooted.

Thanks
Once the GPO is received, the service will actually stop if you select disabled.
Here is a script where you can have all computer names one per line in the "Computers.txt"
Change the "Set service=
::stop, disable and remove
@Echo Off
setlocal
set service=dwmrcs
FOR /F %%c IN (C:\computers.txt) Do (
      Echo stop service %%c
      sc \\%%c stop %service%
      sc \\%%c config %service% start= disabled
      sc \\%%c delete %service%
)

Have a look at this link
https://www.experts-exchange.com/questions/22709273/Stop-a-service-on-all-machines-in-a-file.html?cid=239&anchorAnswerId=19538543#a19538543
Will it automaticly start the service that I enable?
That it will not do.
This script will start a service and all of it's dependents for you, keep in mind that you will need to replace "NetDDE" with the name of the service you want to start. Just paste the code into a text file and then rename it with a .VBS extension, you can run from the command line with the CSCRIPT command.

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

Set colServiceList = objWMIService.ExecQuery _
    ("Select * from Win32_Service where Name='NetDDE'")

For Each objService in colServiceList
    errReturn = objService.StartService()
Next

Wscript.Sleep 20000

Set colServiceList = objWMIService.ExecQuery("Associators of " _
   & "{Win32_Service.Name='NetDDE'} Where " _
        & "AssocClass=Win32_DependentService " & "Role=Dependent" )
For Each objService in colServiceList
    objService.StartService()
Next

This one will do the opposite(Stop Services)

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

Set colServiceList = objWMIService.ExecQuery("Associators of " _
    & "{Win32_Service.Name='NetDDE'} Where " _
        & "AssocClass=Win32_DependentService " & "Role=Antecedent" )

For Each objService in colServiceList
    objService.StopService()
Next

Wscript.Sleep 20000

Set colServiceList = objWMIService.ExecQuery _
        ("Select * from Win32_Service where Name='NetDDE'")
For Each objService in colServiceList
    errReturn = objService.StopService()
Next

You mean you have list of hosts in a file and you want to run this against that file?

WMIC /OUTPUT:"Log_File_Name_Here" /NODE:@"File_Name_Having_Host_Names_Here" /USER:Administrator/PASSWORD:P@ssW0rd SERVICE WHERE Name="Service_Name_Here" CALL StartService

Like:
WMIC /OUTPUT:"C:\ServiceLog.txt" /NODE:@"C:\Computers.txt" /USER:Administrator /PASSWORD:MyPass SERVICE WHERE Name="MESSENGER" CALL StartService

Above statement will START MESSENGER service on all host that are listed in "C:\Computers.txt' file and it will log out the output or status inside C:\ServiceLog.txt file.
Is the strComputer = "." where you set the computer name?
Yes, "strComputer = "." where you set the computer name?"

Using a period means the same as Local meaning your want to run it on your local machine, you can change the period with an IP or even a computer name, however you must have Admin rights on any computer that you want to run it against.
ASKER CERTIFIED SOLUTION
Avatar of Pber
Pber
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
With regards to my previous post:

Change this: strService = "UPHClean"
To match the service in question.

Change this: strSourceOU = "OU=DeskTopOU,"      
to match your desktop OU (including trailing comma) or leave blank to search entire domain (strSourceOU = "")
Do I need to enter my domain name in here? strDomainNC = oRootDSE.Get("defaultNamingContext")

i.e. strDomainNC = oRootDSE.Get("strathconacounty.ab.ca")
Hi Pber, If I want to test this script on just one computer what do I need to change?
RestartService "UPHclean", "SomeMachine"


Sub RestartService(strService,strComputer)
      On Error Resume Next 'just incase

      Set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
      Set objService = objWMI.Get("Win32_Service.Name='" & strService & "'")
      WScript.echo
      WScript.Echo "Restarting " & objService.Name & "..."
     
      i=0
      objService.StopService()
      'wait for service to stop
      Do While objService.state <> "Stopped"
            i=i+1
            WScript.Sleep 10
            Set objService = objWMI.Get("Win32_Service.Name='" & strService & "'") 'requery state
            If i > 500 Then Exit Do 'failsafe
      Loop
      WScript.Echo " * " & strService & ": " & objService.state
     
      i=0
      objService.StartService()
      'wait for service to start
      do While objService.state <> "Running"
            i=i+1
            WScript.Sleep 10
            Set objService = objWMI.Get("Win32_Service.Name='" & strService & "'") 'requery state
            If i > 500 Then Exit Do      'failsafe
      Loop
      WScript.Echo " * " & strService & ": " & objService.state
End sub
Hi Pber, it doesn't seem to work. This is what I ran as a vm script using this command from the command line: cscript servicestop.vbs

RestartService "k9nt", "J2MGPC1"


Sub RestartService(strService,strComputer)
      On Error Resume Next 'just incase

      Set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
      Set objService = objWMI.Get("Win32_Service.Name='" & strService & "'")
      WScript.echo
      WScript.Echo "Restarting " & objService.Name & "..."
     
      i=0
      objService.StopService()
      'wait for service to stop
      Do While objService.state <> "Stopped"
            i=i+1
            WScript.Sleep 10
            Set objService = objWMI.Get("Win32_Service.Name='" & strService & "'") 'requery state
            If i > 500 Then Exit Do 'failsafe
      Loop
      WScript.Echo " * " & strService & ": " & objService.state
     
      i=0
      objService.StartService()
      'wait for service to start
      do While objService.state <> "Running"
            i=i+1
            WScript.Sleep 10
            Set objService = objWMI.Get("Win32_Service.Name='" & strService & "'") 'requery state
            If i > 500 Then Exit Do      'failsafe
      Loop
      WScript.Echo " * " & strService & ": " & objService.state
End sub
Did you have the chance to test this...
WMIC /OUTPUT:"Log_File_Name_Here" /NODE:@"File_Name_Having_Host_Names_Here" /USER:Administrator/PASSWORD:P@ssW0rd SERVICE WHERE Name="Service_Name_Here" CALL StartService

Like:
WMIC /OUTPUT:"C:\ServiceLog.txt" /NODE:@"C:\Computers.txt" /USER:Administrator /PASSWORD:MyPass SERVICE WHERE Name="MESSENGER" CALL StartService

Above statement will START MESSENGER service on all host that are listed in "C:\Computers.txt' file and it will log out the output or status inside C:\ServiceLog.txt file.
remove the on error resume next and change out the error
Hi Pber,
I get this error when I remove error resume next:

C:\CAPTURE.vbs(8, 7) SWbemServicesEx: Not found
bsharath, I have not had a chance to test this script. I have been testing Pber's because it query's active directory. I would need to create a text file with all the computers in active directory other wise.
What is the service and what is the computer?

RestartService "k9nt", "J2MGPC1"

The format is:

RestartService "service name", "Computername"
What would be even easier would be to do an export of your computer objects in AD to a text file, then this text file would contain all of the computer names in the domain. You can then use this text file as an input into the script which will loop through each one and do what you want with the services. This would be better because then you could add error checking into your script. If you don't and your script fails you will have no way of knowing where it left off before it bombed. This would be more efficient then ripping the computer names out of the domain and then trying to start and stop their services however it's just a matter of programming style I guess.
k9nt might not be the Service name of the service itself.

Do a:

SC Query and look for the SERVICE_NAME of the k9nt service.  That is the value that should be presented to the script.
Thanks MeCanHelp, how do you export the computer objects to a text file?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
First , thanks everyone for your help you have all been great. I think I am getting close to where I need to be.

I have managed to figure out how to export computer names from active directory now I just need to know how to get the scrip to read them.

Cheers,
rory
From what I researched, the SERVICE_NAME for k9nt is K9.

So  try this:


RestartService "k9", "J2MGPC1"
That works Pber, thanks!
Set oFSO = CreateObject("Scripting.FileSystemObject")
sFile = "your text file"

If oFSO.FileExists(sFile) Then
Set oFile = oFSO.OpenTextFile(sFile, 1)

Do While Not oFile.AtEndOfStream
   sText = oFile.ReadLine
         strComputer = sText

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

         Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name='NetDDE'")

      For Each objService in colServiceList
         errReturn = objService.StartService()
      Next

   Wscript.Sleep 20000

   Set colServiceList = objWMIService.ExecQuery("Associators of " _
& "{Win32_Service.Name='NetDDE'} Where " _
& "AssocClass=Win32_DependentService " & "Role=Dependent" )

   For Each objService in colServiceList
      objService.StartService()
   Next

Loop

oFile.Close

Else
   WScript.Echo "The file was not there."
End If
Great news.  

The original script that I sent should then enum all the computers and bounce the service.
I think I have figured out he easiest way to do this "with lots of help". What I need to know now is how I can run these commands from a batch file:

psexec \\j2mgpc1 k9nt remove
psexec \\j2mgpc1 sc config servicename start= auto
psexec \\j2mgpc1 net start servicename

Thanks,
Rory
Forced accept.

Computer101
EE Admin