Script vbs to restart a service if it is "stoppered"

Asked

Viewed 331 times

0

I created a vbs script to restart the service if it is stopped. However it does not work, I tried to do a by . bat more without including in the schedules tasks.

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

Set colRunningServices = objWMIService.ExecQuery("Select * from Win32_Service")

For Each objService in colRunningServices

 if (objService.State="Stopped") and (objService.DisplayName="Print Spooler") then

  Wscript.Echo "Service Status:  "& objService.State &""
  objService.StartService()
         end if  
Next
  • Is it a requirement to use vbs? Or can you do it some other way?

  • can be made another way, the vbs and batch were attempts, at first I thought it was the code.

2 answers

0

If you only need to start it if it is stopped, just have it start in a bat run with administrator permission.

net start Spooler

If return (%errorlevel%) 0 worked, if return 2 is pq an error has occurred. One of the error cases is if the service is already active. Which wouldn’t be a problem.

Reply in English

0


inserir a descrição da imagem aqui


Suggestion using your adapting the service status check to when stop startar again:


set wmi = GetObject("winmgmts://./root/cimv2")
qry = "SELECT * FROM Win32_Service WHERE Name='Spooler'"
for each i in wmi.ExecQuery(qry)
   if i.State = "Stopped" then i.StartService
   do until wmi.ExecQuery(qry & " AND State='Running'").Count > 0
   wscript.sleep 100
   loop
next
NomeServico="Spooler de Impress"+chr(227)+"o"
for each wmi in wmi.ExecQuery(qry)
   if (wmi.State="Running") and (wmi.DisplayName=NomeServico) then
      Wscript.Echo  vbCrLf &"        Service Name: "&wmi.Name&""& vbCrLf &_
      "      Service Status: "&wmi.State&""& vbCrLf &_
      "Service Display Name: "&wmi.DisplayName&""
   end if  
next

inserir a descrição da imagem aqui


Browser other questions tagged

You are not signed in. Login or sign up in order to post.