Solved

Script to enable and disable service on computers in a domain

Posted on 2007-11-23
34
508 Views
Last Modified: 2010-05-10
Does any one have a script that will enable/disable, start/stop services on all the desktops in a domain?
0
Comment
Question by:rorybrady
  • 12
  • 12
  • 5
  • +2
34 Comments
 
LVL 26

Expert Comment

by:Pber
ID: 20339213
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

0
 
LVL 26

Expert Comment

by:Pber
ID: 20339227
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.
0
 

Author Comment

by:rorybrady
ID: 20339394
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
0
 
LVL 26

Expert Comment

by:Pber
ID: 20339433
Once the GPO is received, the service will actually stop if you select disabled.
0
 
LVL 11

Expert Comment

by:bsharath
ID: 20339465
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
http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Q_22709273.html?cid=239#a19538543
0
 

Author Comment

by:rorybrady
ID: 20339500
Will it automaticly start the service that I enable?
0
 
LVL 26

Expert Comment

by:Pber
ID: 20339538
That it will not do.
0
 
LVL 4

Expert Comment

by:MeCanHelp
ID: 20339623
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

0
 
LVL 11

Expert Comment

by:bsharath
ID: 20339636
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.
0
 

Author Comment

by:rorybrady
ID: 20339642
Is the strComputer = "." where you set the computer name?
0
 
LVL 4

Expert Comment

by:MeCanHelp
ID: 20339720
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.
0
 
LVL 26

Accepted Solution

by:
Pber earned 250 total points
ID: 20339726
This script will find all the computers in the domain and restart a service.  You can comment out the required code in the RestartService routine to just stop or start.

strSourceOU = "OU=DeskTopOU,"      'include OU= or CN= and trailing comma - replace this
strLDAP = "(&(objectClass=Computer))"

set oRootDSE = GetObject("LDAP://RootDSE")
strDomainNC = oRootDSE.Get("defaultNamingContext")
set oRootDSE = Nothing

Set oConnection   = CreateObject("ADODB.Connection")
oConnection.Provider   = "ADsDSOObject"
oConnection.Open "Active Directory Provider"

Set oCommand = CreateObject("ADODB.Command")
Set oCommand.ActiveConnection = oConnection

strQuery = "<LDAP://"& strSourceOU & strDomainNC &">;" & strLDAP & ";AdsPath;subTree"
WScript.Echo strQuery
oCommand.CommandText = strQuery  
oCommand.Properties("Page Size") = 1000

Set oRecordSet = oCommand.Execute

if not oRecordSet.Eof Then
      WScript.Echo "- Object Count: " & oRecordSet.RecordCount
      While Not oRecordSet.Eof
            Set objcomp = GetObject(oRecordSet.Fields("AdsPath").Value)
            'WScript.Echo objcomp.name & " - " & objcomp.description
            
            strComputer  = Replace(objcomp.name,"CN=","")
            WScript.Echo strComputer
            
            strService = "UPHClean"

            ' Restart target service
            RestartService strService, strComputer
            
            oRecordSet.MoveNext
      Wend
      Set objcomp = nothing
end If

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
0
 
LVL 26

Expert Comment

by:Pber
ID: 20339744
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 = "")
0
 

Author Comment

by:rorybrady
ID: 20339770
Do I need to enter my domain name in here? strDomainNC = oRootDSE.Get("defaultNamingContext")

i.e. strDomainNC = oRootDSE.Get("strathconacounty.ab.ca")
0
 

Author Comment

by:rorybrady
ID: 20339781
Hi Pber, If I want to test this script on just one computer what do I need to change?
0
 
LVL 26

Expert Comment

by:Pber
ID: 20339796
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
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:rorybrady
ID: 20339978
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
0
 
LVL 11

Expert Comment

by:bsharath
ID: 20339994
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.
0
 
LVL 26

Expert Comment

by:Pber
ID: 20339995
remove the on error resume next and change out the error
0
 

Author Comment

by:rorybrady
ID: 20340010
Hi Pber,
I get this error when I remove error resume next:

C:\CAPTURE.vbs(8, 7) SWbemServicesEx: Not found
0
 

Author Comment

by:rorybrady
ID: 20340015
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.
0
 
LVL 26

Expert Comment

by:Pber
ID: 20340020
What is the service and what is the computer?

RestartService "k9nt", "J2MGPC1"

The format is:

RestartService "service name", "Computername"
0
 
LVL 4

Expert Comment

by:MeCanHelp
ID: 20340029
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.
0
 
LVL 26

Expert Comment

by:Pber
ID: 20340046
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.
0
 

Author Comment

by:rorybrady
ID: 20340058
Thanks MeCanHelp, how do you export the computer objects to a text file?
0
 
LVL 4

Assisted Solution

by:MeCanHelp
MeCanHelp earned 250 total points
ID: 20340202
Step-by-Step Guide to Bulk Import and Export to Active Directory
http://technet.microsoft.com/en-us/library/Bb727091.aspx
0
 

Author Comment

by:rorybrady
ID: 20340211
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
0
 
LVL 26

Expert Comment

by:Pber
ID: 20340326
From what I researched, the SERVICE_NAME for k9nt is K9.

So  try this:


RestartService "k9", "J2MGPC1"
0
 

Author Comment

by:rorybrady
ID: 20340341
That works Pber, thanks!
0
 
LVL 4

Expert Comment

by:MeCanHelp
ID: 20340345
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
0
 
LVL 26

Expert Comment

by:Pber
ID: 20340353
Great news.  

The original script that I sent should then enum all the computers and bounce the service.
0
 

Author Comment

by:rorybrady
ID: 20353258
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
0
 
LVL 1

Expert Comment

by:Computer101
ID: 20521755
Forced accept.

Computer101
EE Admin
0

Featured Post

Want to promote your upcoming event?

Attending an event? Speaking at a conference? Or exhibiting at a tradeshow? Easily inform your contacts by using a promotional banner in your email signature. This will ensure your organization’s most important contacts are in the know.

Join & Write a Comment

Recently Microsoft released a brand new function called CONCAT. It's supposed to replace its predecessor CONCATENATE. But how does it work? And what's new? In this article, we take a closer look at all of this - we even included an exercise file for…
Today, still in the boom of Apple, PC's and products, nearly 50% of the computer users use Windows as graphical operating systems. If you are among those users who love windows, but are grappling to keep the system's hard drive optimized, then you s…
With the advent of Windows 10, Microsoft is pushing a Get Windows 10 icon into the notification area (system tray) of qualifying computers. There are many reasons for wanting to remove this icon. This two-part Experts Exchange video Micro Tutorial s…
The Task Scheduler is a powerful tool that is built into Windows. It allows you to schedule tasks (actions) on a recurring basis, such as hourly, daily, weekly, monthly, at log on, at startup, on idle, etc. This video Micro Tutorial is a brief intro…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now