Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 680
  • Last Modified:

Scan all machine in a txt file and if live then check 6 services if all started and Automatic do nothing else. Start then and set them to Automatic and if it fails email me.

Hi,

Scan all machine in a txt file and if live then check 6 services if all started and Automatic do nothing else. Start then and set them to Automatic and if it fails email me.

If it was stooed and start and if manual and the script changed to Automatic i want an email. So i know the script did a change. if for some reason not able to start or set automatic for the 6 services. i want an email to be sent. Not 1 email for 1 computer but after all scanned 1 email for all. Interval of 4 hrs per scan.
fastest as possible please.

regards
Sharath
0
bsharath
Asked:
bsharath
  • 65
  • 53
  • 3
1 Solution
 
Meir RivkinFull stack Software EngineerCommented:
the 6 services are hard coded, or should be read from file as well?
0
 
bsharathAuthor Commented:
They are hardcoded...
0
 
Meir RivkinFull stack Software EngineerCommented:
add machines list to machines.txt (machine name in each line)
change SERVICES_LIST (services names separated by coma)
Option Explicit
const SERVICES_LIST = "Apache2.2,Dfs"

dim objFileLog,objFSO,objFile
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
strQuery = "Select * from Win32_Service where Name = '"

for each service in Split(SERVICES_LIST, ",")
	strQuery = strQuery & service & "' or Name = '"
next

strQuery = strQuery & vbNewLine
strQuery = Replace(strQuery, "or Name = '" & vbNewLine, "") 

set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile("c:\temp\machines.txt", 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)

set objFileLog = objFSO.CreateTextFile("c:\temp\services.log", 2)

for each strComputer in arrMachines
	objFileLog.WriteLine
	objFileLog.WriteLine "Machine: [" & strComputer & "]"
	if Ping(strComputer) = true then
		Set objWMIService = GetObject("winmgmts:" _
		& "{impersonationLevel=impersonate}!\\" _
		& strComputer & "\root\cimv2")
		Set colListOfServices = objWMIService.ExecQuery(strQuery)

		For Each objService in colListOfServices
			objFileLog.WriteLine
			objFileLog.WriteLine "Service: [" & objService.DisplayName & "]"
			
			if objService.State <> "Running" then
				objFileLog.WriteLine "Running service [" & objService.DisplayName & "] ..."
				StartService objService		
			else
				objFileLog.WriteLine objService.DisplayName & " is already running"
			end if

			if objService.StartMode = "Manual" then
				objFileLog.WriteLine "Change StartMode to Auto"
				objService.ChangeStartMode("Automatic")
			else
				objFileLog.WriteLine objService.DisplayName & " is already set as Auto"
			end if
		Next
	else
		objFileLog.WriteLine strComputer & " is unaccesible."
	end if
Next

objFile.Close

wscript.echo "Complete"

sub StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
	
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				objFileLog.WriteLine objService.DisplayName & " was started successfully."
				exit sub
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		objFileLog.WriteLine "The " & objService.DisplayName & _
			" service is in state " & objService.State & ", Cannot start Service"
	else
		objFileLog.WriteLine objService.DisplayName & _
			" is in state " & objService.State & ", Cannot start Service"
	end if
end sub

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 The Evil-ution of Network Security Threats

What are the hacks that forever changed the security industry? To answer that question, we created an exciting new eBook that takes you on a trip through hacking history. It explores the top hacks from the 80s to 2010s, why they mattered, and how the security industry responded.

 
Meir RivkinFull stack Software EngineerCommented:
take this one
Option Explicit
const SERVICES_LIST = "Apache2.2,Dfs"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
strQuery = "Select * from Win32_Service where Name = '"

for each service in Split(SERVICES_LIST, ",")
	strQuery = strQuery & service & "' or Name = '"
next

strQuery = strQuery & vbNewLine
strQuery = Replace(strQuery, "or Name = '" & vbNewLine, "") 

set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

for each strComputer in arrMachines
	objFileLog.WriteLine
	objFileLog.WriteLine "Machine: [" & strComputer & "]"
	if Ping(strComputer) = true then
		Set objWMIService = GetObject("winmgmts:" _
		& "{impersonationLevel=impersonate}!\\" _
		& strComputer & "\root\cimv2")
		Set colListOfServices = objWMIService.ExecQuery(strQuery)

		For Each objService in colListOfServices
			objFileLog.WriteLine
			objFileLog.WriteLine "Service: [" & objService.DisplayName & "]"
			
			if objService.State <> "Running" then
				objFileLog.WriteLine "Running service [" & objService.DisplayName & "] ..."
				StartService objService		
			else
				objFileLog.WriteLine objService.DisplayName & " is already running"
			end if

			if objService.StartMode = "Manual" then
				objFileLog.WriteLine "Change StartMode to Auto"
				objService.ChangeStartMode("Automatic")
			else
				objFileLog.WriteLine objService.DisplayName & " is already set as Auto"
			end if
		Next
	else
		objFileLog.WriteLine strComputer & " is unaccesible."
	end if
Next

objFile.Close

wscript.echo "Complete"

sub StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
	
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				objFileLog.WriteLine objService.DisplayName & " was started successfully."
				exit sub
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		objFileLog.WriteLine "The " & objService.DisplayName & _
			" service is in state " & objService.State & ", Cannot start Service"
	else
		objFileLog.WriteLine objService.DisplayName & _
			" is in state " & objService.State & ", Cannot start Service"
	end if
end sub

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
I get this

---------------------------
Windows Script Host
---------------------------
Script:      D:\Services start and email.vbs
Line:      29
Char:      3
Error:      The remote server machine does not exist or is unavailable: 'GetObject'
Code:      800A01CE
Source:       Microsoft VBScript runtime error

---------------------------
OK  
---------------------------

is the emailing option added?
0
 
Meir RivkinFull stack Software EngineerCommented:
forgot the emailing, i'll update the script.
Option Explicit
const SERVICES_LIST = "Apache2.2,Dfs,hkmsvc"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
strQuery = "Select * from Win32_Service where Name = '"

for each service in Split(SERVICES_LIST, ",")
	strQuery = strQuery & service & "' or Name = '"
next

strQuery = strQuery & vbNewLine
strQuery = Replace(strQuery, "or Name = '" & vbNewLine, "") 

set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

for each strComputer in arrMachines
	objFileLog.WriteLine
	objFileLog.WriteLine "Machine: [" & strComputer & "]"
	if Ping(strComputer) = true then
		Set objWMIService = GetObject("winmgmts:" _
		& "{impersonationLevel=impersonate}!\\" _
		& strComputer & "\root\cimv2")
		Set colListOfServices = objWMIService.ExecQuery(strQuery)

		For Each objService in colListOfServices
			objFileLog.WriteLine
			objFileLog.WriteLine "Service: [" & objService.DisplayName & "]"
			
			if objService.State <> "Running" then
				objFileLog.WriteLine "Running service [" & objService.DisplayName & "] ..."
				StartService objService		
			else
				objFileLog.WriteLine objService.DisplayName & " is already running"
			end if

			if objService.StartMode = "Manual" then
				objFileLog.WriteLine "Change StartMode to Auto"
				objService.ChangeStartMode("Automatic")
			else
				objFileLog.WriteLine objService.DisplayName & " is already set as Auto"
			end if
		Next
	else
		objFileLog.WriteLine strComputer & " is unaccesible."
	end if
Next

objFile.Close

NotifyByEmail "Services Email Notification", objFSO.OpenTextFile(LOG_FILE).ReadAll

wscript.echo "Complete"

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

sub StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
	
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				objFileLog.WriteLine objService.DisplayName & " was started successfully."
				exit sub
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		objFileLog.WriteLine "The " & objService.DisplayName & _
			" service is in state " & objService.State & ", Cannot start Service"
	else
		objFileLog.WriteLine objService.DisplayName & _
			" is in state " & objService.State & ", Cannot start Service"
	end if
end sub

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
Meir RivkinFull stack Software EngineerCommented:
regarding the error: The remote server machine does not exist or is unavailable: 'GetObject.
i've updated the script to overcome this probelm, however, check the following constraints:

1. You cannot connect to computer running XP Home.
2. An NT computer cannot connect to OS later than W2k.
3. A W2k3 computer cannot connect to Win9x.
4. To connect to W2k Server SP4 you must set impersonation level to
Impersonate.
5. W2k computers must have SP2 to connect to XP or above.
6. W2k3 can only connect to Win9x and NT if credentials supplied.
7. To connect to XP or W2k3 you must set authentication level to Pkt.
taken from (http://www.webmasterkb.com/Uwe/Forum.aspx/vbscript/20270/REading-a-remote-file-using-WMI-unable-to-connect-to-remote-machine)
Option Explicit
const SERVICES_LIST = "Apache2.2,Dfs,hkmsvc"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
strQuery = "Select * from Win32_Service where Name = '"

for each service in Split(SERVICES_LIST, ",")
	strQuery = strQuery & service & "' or Name = '"
next

strQuery = strQuery & vbNewLine
strQuery = Replace(strQuery, "or Name = '" & vbNewLine, "") 

set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

for each strComputer in arrMachines
	objFileLog.WriteLine
	objFileLog.WriteLine "Machine: [" & strComputer & "]"
	if Ping(strComputer) = true then
		Set objWMIService = GetObject("winmgmts:" _
		& "{impersonationLevel=impersonate,authenticationLevel=Pkt}!\\" _
		& strComputer & "\root\cimv2")
		Set colListOfServices = objWMIService.ExecQuery(strQuery)

		For Each objService in colListOfServices
			objFileLog.WriteLine
			objFileLog.WriteLine "Service: [" & objService.DisplayName & "]"
			
			if objService.State <> "Running" then
				objFileLog.WriteLine "Running service [" & objService.DisplayName & "] ..."
				StartService objService		
			else
				objFileLog.WriteLine objService.DisplayName & " is already running"
			end if

			if objService.StartMode = "Manual" then
				objFileLog.WriteLine "Change StartMode to Auto"
				objService.ChangeStartMode("Automatic")
			else
				objFileLog.WriteLine objService.DisplayName & " is already set as Auto"
			end if
		Next
	else
		objFileLog.WriteLine strComputer & " is unaccesible."
	end if
Next

objFile.Close

NotifyByEmail "Services Email Notification", objFSO.OpenTextFile(LOG_FILE).ReadAll

wscript.echo "Complete"

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

sub StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
	
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				objFileLog.WriteLine objService.DisplayName & " was started successfully."
				exit sub
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		objFileLog.WriteLine "The " & objService.DisplayName & _
			" service is in state " & objService.State & ", Cannot start Service"
	else
		objFileLog.WriteLine objService.DisplayName & _
			" is in state " & objService.State & ", Cannot start Service"
	end if
end sub

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
I get this

---------------------------
Windows Script Host
---------------------------
Script:      D:\Services start and email.vbs
Line:      29
Char:      3
Error:      The remote server machine does not exist or is unavailable: 'GetObject'
Code:      800A01CE
Source:       Microsoft VBScript runtime error

---------------------------
OK  
---------------------------

if this error can be skipped please do it
This machine is online and has win xp sp3
0
 
Meir RivkinFull stack Software EngineerCommented:
try this
Option Explicit
const SERVICES_LIST = "Apache2.2,Dfs,hkmsvc"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
strQuery = "Select * from Win32_Service where Name = '"

for each service in Split(SERVICES_LIST, ",")
	strQuery = strQuery & service & "' or Name = '"
next

strQuery = strQuery & vbNewLine
strQuery = Replace(strQuery, "or Name = '" & vbNewLine, "") 

set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

for each strComputer in arrMachines
	objFileLog.WriteLine
	objFileLog.WriteLine "Machine: [" & strComputer & "]"
	if Ping(strComputer) = true then
on error resume next
		Set objWMIService = GetObject("winmgmts:" _
		& "{impersonationLevel=impersonate,authenticationLevel=Pkt}!\\" _
		& strComputer & "\root\cimv2")
		Set colListOfServices = objWMIService.ExecQuery(strQuery)

		For Each objService in colListOfServices
			objFileLog.WriteLine
			objFileLog.WriteLine "Service: [" & objService.DisplayName & "]"
			
			if objService.State <> "Running" then
				objFileLog.WriteLine "Running service [" & objService.DisplayName & "] ..."
				StartService objService		
			else
				objFileLog.WriteLine objService.DisplayName & " is already running"
			end if

			if objService.StartMode = "Manual" then
				objFileLog.WriteLine "Change StartMode to Auto"
				objService.ChangeStartMode("Automatic")
			else
				objFileLog.WriteLine objService.DisplayName & " is already set as Auto"
			end if
		Next
	else
		objFileLog.WriteLine strComputer & " is unaccesible."
	end if
Next

objFile.Close

NotifyByEmail "Services Email Notification", objFSO.OpenTextFile(LOG_FILE).ReadAll

wscript.echo "Complete"

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

sub StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
	
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				objFileLog.WriteLine objService.DisplayName & " was started successfully."
				exit sub
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		objFileLog.WriteLine "The " & objService.DisplayName & _
			" service is in state " & objService.State & ", Cannot start Service"
	else
		objFileLog.WriteLine objService.DisplayName & _
			" is in state " & objService.State & ", Cannot start Service"
	end if
end sub

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Thanks
it emails all thats got as report.
What i want is the email log should have just this
1. Machines that were stooed and the script started it
2. Machines that had the service disabled\manual and script made it automatic
3. Machines that the script tried a change but failed to change

i dont want the success or timed out machine details
0
 
Meir RivkinFull stack Software EngineerCommented:
try this
Option Explicit
const SERVICES_LIST = "Apache2.2,Dfs,hkmsvc"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
strQuery = "Select * from Win32_Service where Name = '"

for each service in Split(SERVICES_LIST, ",")
	strQuery = strQuery & service & "' or Name = '"
next

strQuery = strQuery & vbNewLine
strQuery = Replace(strQuery, "or Name = '" & vbNewLine, "") 

set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

for each strComputer in arrMachines
	objFileLog.WriteLine
	objFileLog.WriteLine "Machine: [" & strComputer & "]"
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:" _
		& "{impersonationLevel=impersonate,authenticationLevel=Pkt}!\\" _
		& strComputer & "\root\cimv2")
		if Err.Number <> 0 then
			objFileLog.WriteLine strComputer & " is unaccesible."
		else
			Set colListOfServices = objWMIService.ExecQuery(strQuery)

			For Each objService in colListOfServices
				objFileLog.WriteLine
				objFileLog.WriteLine "Service: [" & objService.DisplayName & "]"
				
				if objService.State <> "Running" then
					objFileLog.WriteLine "Running service [" & objService.DisplayName & "] ..."
					StartService objService		
	'			else
	'				objFileLog.WriteLine objService.DisplayName & " is already running"
				end if

				if objService.StartMode = "Manual" then
					objFileLog.WriteLine "Change StartMode to Auto"
					objService.ChangeStartMode("Automatic")
	'			else
	'				objFileLog.WriteLine objService.DisplayName & " is already set as Auto"
				end if
			Next
		end if
	else
		objFileLog.WriteLine strComputer & " is unaccesible."
	end if
Next

objFile.Close

NotifyByEmail "Services Email Notification", objFSO.OpenTextFile(LOG_FILE).ReadAll

wscript.echo "Complete"

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

sub StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
	
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				objFileLog.WriteLine objService.DisplayName & " was started successfully."
				exit sub
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		objFileLog.WriteLine "The " & objService.DisplayName & _
			" service is in state " & objService.State & ", Cannot start Service"
	else
		objFileLog.WriteLine objService.DisplayName & _
			" is in state " & objService.State & ", Cannot start Service"
	end if
end sub

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Better but still get the
is unaccesible. emails
and some machines data like this

Machine: [Dev82]
Service: [Sophos Agent]
Service: [Sophos AutoUpdate Service]
Service: [Sophos Message Router]

not sure why i get this. no status as it did any thing
0
 
Meir RivkinFull stack Software EngineerCommented:
try this
Option Explicit
const SERVICES_LIST = "Dfs,hkmsvc"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile, logContent
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
strQuery = "Select * from Win32_Service where Name = '"

for each service in Split(SERVICES_LIST, ",")
	strQuery = strQuery & service & "' or Name = '"
next

strQuery = strQuery & vbNewLine
strQuery = Replace(strQuery, "or Name = '" & vbNewLine, "") 

set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

dim serviceChanged
dim machineLogResult

for each strComputer in arrMachines
	machineLogResult = machineLogResult & "Machine: [" & strComputer & "]" & vbNewLine
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:" _
		& "{impersonationLevel=impersonate,authenticationLevel=Pkt}!\\" _
		& strComputer & "\root\cimv2")
		if Err.Number <> 0 then 
			logContent = logContent &  strComputer & " is unaccesible." & vbNewLine
		else
			Set colListOfServices = objWMIService.ExecQuery(strQuery)

			For Each objService in colListOfServices
				serviceChanged = false
				machineLogResult = machineLogResult & vbNewLine
				machineLogResult = machineLogResult &  "Service: [" & objService.DisplayName & "]" & vbNewLine
				
				if objService.State <> "Running" then
					machineLogResult = machineLogResult & "Running service [" & objService.DisplayName & "] ..." & vbNewLine
					StartService objService
					serviceChanged = true
				end if

				if objService.StartMode = "Manual" then
					machineLogResult = machineLogResult & "Change StartMode to Auto" & vbNewLine
					objService.ChangeStartMode("Automatic")
					serviceChanged = true
				end if
				
				if serviceChanged = true then
					logContent = logContent & machineLogResult & vbNewLine
				end if
			Next
		end if
	else
		logContent = logContent & strComputer & " is unaccesible." & vbNewLine
	end if
Next

if Trim(logContent) <> "" then
	set objFileLog = objFSO.CreateTextFile("c:\temp\1.log", 2)
	objFileLog.Write logContent
	objFileLog.Close

	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

sub StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
	
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				logContent = logContent & objService.DisplayName & " was started successfully." & vbNewLine
				exit sub
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		logContent = logContent & "The " & objService.DisplayName & " service is in state " & objService.State & ", Cannot start Service" & vbNewLine
	else
		logContent = logContent & objService.DisplayName & " is in state " & objService.State & ", Cannot start Service" & vbNewLine
	end if
end sub

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
Meir RivkinFull stack Software EngineerCommented:
this is the updated one:
Option Explicit
const SERVICES_LIST = "Dfs,hkmsvc"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile, logContent
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
strQuery = "Select * from Win32_Service where Name = '"

for each service in Split(SERVICES_LIST, ",")
	strQuery = strQuery & service & "' or Name = '"
next

strQuery = strQuery & vbNewLine
strQuery = Replace(strQuery, "or Name = '" & vbNewLine, "") 

set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

dim serviceChanged
dim machineLogResult

for each strComputer in arrMachines
	machineLogResult = machineLogResult & "Machine: [" & strComputer & "]" & vbNewLine
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:" _
		& "{impersonationLevel=impersonate,authenticationLevel=Pkt}!\\" _
		& strComputer & "\root\cimv2")
		if Err.Number <> 0 then 
			logContent = logContent &  strComputer & " is unaccesible." & vbNewLine
		else
			Set colListOfServices = objWMIService.ExecQuery(strQuery)

			For Each objService in colListOfServices
				serviceChanged = false
				machineLogResult = machineLogResult & vbNewLine
				machineLogResult = machineLogResult &  "Service: [" & objService.DisplayName & "]" & vbNewLine
				
				if objService.State <> "Running" then
					machineLogResult = machineLogResult & "Running service [" & objService.DisplayName & "] ..." & vbNewLine
					StartService objService
					serviceChanged = true
				end if

				if objService.StartMode = "Manual" then
					machineLogResult = machineLogResult & "Change StartMode to Auto" & vbNewLine
					objService.ChangeStartMode("Automatic")
					serviceChanged = true
				end if
				
				if serviceChanged = true then
					logContent = logContent & machineLogResult & vbNewLine
				end if
			Next
		end if
	else
		logContent = logContent & strComputer & " is unaccesible." & vbNewLine
	end if
Next

if Trim(logContent) <> "" then
	set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
	objFileLog.Write logContent
	objFileLog.Close

	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

sub StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
	
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				logContent = logContent & objService.DisplayName & " was started successfully." & vbNewLine
				exit sub
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		logContent = logContent & "The " & objService.DisplayName & " service is in state " & objService.State & ", Cannot start Service" & vbNewLine
	else
		logContent = logContent & objService.DisplayName & " is in state " & objService.State & ", Cannot start Service" & vbNewLine
	end if
end sub

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
I still get
is unaccesible.

i dont want to get the non pinging machines. I want to get permission errors
0
 
Meir RivkinFull stack Software EngineerCommented:
so no log if the machine is accessible?
0
 
bsharathAuthor Commented:
I dont want a log if its not accessible.
if a service is manual and started the script does not change to Autmatic
0
 
Meir RivkinFull stack Software EngineerCommented:
>>if a service is manual and started the script does not change to Autmatic

so after starting the service, i need to verify that the mode was changed to Auto? and if not then change it?
0
 
bsharathAuthor Commented:
Yes i want to check the status first and then change it and log the change...
0
 
Meir RivkinFull stack Software EngineerCommented:
try this:
Option Explicit
const SERVICES_LIST = "Dfs,hkmsvc"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile, logContent
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
strQuery = "Select * from Win32_Service where Name = '"

for each service in Split(SERVICES_LIST, ",")
	strQuery = strQuery & service & "' or Name = '"
next

strQuery = strQuery & vbNewLine
strQuery = Replace(strQuery, "or Name = '" & vbNewLine, "") 

set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

dim serviceChanged
dim machineLogResult

for each strComputer in arrMachines
	machineLogResult = machineLogResult & "Machine: [" & strComputer & "]" & vbNewLine
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:" _
		& "{impersonationLevel=impersonate,authenticationLevel=Pkt}!\\" _
		& strComputer & "\root\cimv2")
		if Err.Number = 0 then 
			Set colListOfServices = objWMIService.ExecQuery(strQuery)

			For Each objService in colListOfServices
				serviceChanged = false
				machineLogResult = machineLogResult & vbNewLine
				machineLogResult = machineLogResult &  "Service: [" & objService.DisplayName & "]" & vbNewLine
				
				if objService.State <> "Running" then
					machineLogResult = machineLogResult & "Running service [" & objService.DisplayName & "] ..." & vbNewLine
					StartService objService
					serviceChanged = true
				end if

				if objService.StartMode = "Manual" then
					machineLogResult = machineLogResult & "Change StartMode to Auto" & vbNewLine
					objService.ChangeStartMode("Automatic")
					serviceChanged = true
				end if
				
				if serviceChanged = true then
					logContent = logContent & machineLogResult & vbNewLine
				end if
			Next
		end if
	end if
Next

if Trim(logContent) <> "" then
	set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
	objFileLog.Write logContent
	objFileLog.Close

	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

sub StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
	
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				logContent = logContent & objService.DisplayName & " was started successfully." & vbNewLine
				exit sub
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		logContent = logContent & "The " & objService.DisplayName & " service is in state " & objService.State & ", Cannot start Service" & vbNewLine
	else
		logContent = logContent & objService.DisplayName & " is in state " & objService.State & ", Cannot start Service" & vbNewLine
	end if
end sub

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Still if a service is disabled it does not make it strated and automatic
If manual or automatic 2 services were not changed..

Until now i did not get the Outlook security message as allow or deny. only now i get this
0
 
Meir RivkinFull stack Software EngineerCommented:
check this please
Option Explicit
const SERVICES_LIST = "Dfs,hkmsvc"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile, logContent
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
strQuery = "Select * from Win32_Service where Name = '"

for each service in Split(SERVICES_LIST, ",")
	strQuery = strQuery & service & "' or Name = '"
next

strQuery = strQuery & vbNewLine
strQuery = Replace(strQuery, "or Name = '" & vbNewLine, "") 

set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

dim serviceChanged
dim machineLogResult

for each strComputer in arrMachines
	machineLogResult = machineLogResult & "Machine: [" & strComputer & "]" & vbNewLine
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:" _
		& "{impersonationLevel=impersonate,authenticationLevel=Pkt}!\\" _
		& strComputer & "\root\cimv2")
		if Err.Number = 0 then 
			Set colListOfServices = objWMIService.ExecQuery(strQuery)

			For Each objService in colListOfServices
				serviceChanged = false
				machineLogResult = machineLogResult & vbNewLine
				machineLogResult = machineLogResult &  "Service: [" & objService.DisplayName & "]" & vbNewLine
				
				if objService.StartMode <> "Auto" then
					machineLogResult = machineLogResult & "Change StartMode to Auto" & vbNewLine
					objService.ChangeStartMode("Automatic")
					serviceChanged = true
				end if
				
				if objService.State <> "Running" then
					machineLogResult = machineLogResult & StartService(objService)
					serviceChanged = true
				end if

				if serviceChanged = true then
					logContent = logContent & machineLogResult & vbNewLine
				end if
			Next
		end if
	end if
Next

if Trim(logContent) <> "" then
	set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
	objFileLog.Write logContent
	objFileLog.Close

	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

function StartService(objService)
	dim Result,WaitFor,log
	Result = objService.StartService()
	
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = log & objService.DisplayName & " was started successfully." & vbNewLine
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		log = log & "The " & objService.DisplayName & " service is in state " & objService.State & ", Cannot start Service" & vbNewLine
	else
		log = log & objService.DisplayName & " is in state " & objService.State & ", Cannot start Service" & vbNewLine
	end if
	
	StartService = log
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Manual stopped
Started manual
Stopped manual

the above 3 did not change
I still get the outlook accept deny warning
0
 
Meir RivkinFull stack Software EngineerCommented:
i don't understand your comments.
please describe the exact scenario of the problem.
regarding outlook, it's the same function i use in all the scripts i've posted (and you used) so nothing to add there.
0
 
bsharathAuthor Commented:
If the service is in any of these 2 states it does not change to started and automatic

Manual and stopped
Started and manual

Manual and stopped it has to change to automatic and started
Started and manual it has to change to automatic and started


0
 
Meir RivkinFull stack Software EngineerCommented:
are you sure?
i double checked it on any scenario and it always set it to auto and start the service.
did u refresh the services list after running the script? (sounds trivial but it really should work unless error occurs)
0
 
Meir RivkinFull stack Software EngineerCommented:
sorry, my mistake, i'll udpate the script asap ....

0
 
Meir RivkinFull stack Software EngineerCommented:
here it is:
Option Explicit
const SERVICES_LIST = "dfs,DFSR"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	logResult = HandleMachineServices(strComputer)
	if logResult <> "" then
		logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
	end if
Next

if Trim(logContent) <> "" then
	set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
	objFileLog.Write logContent
	objFileLog.Close

	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

function HandleMachineServices(strComputer)
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,authenticationLevel=Pkt}!\\" & strComputer & "\root\cimv2")
		if Err.Number = 0 then 
			for each strService in Split(SERVICES_LIST, ",")
			
				Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service where Name = '" & Trim(strService) & "'")
				
				For Each objService in colListOfServices
					if objService.StartMode <> "Auto" then
						serviceLog = "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						serviceLog = serviceLog & StartService(objService)
					end if
					
					if serviceLog <> "" then
						machineLog = machineLog &  "Service: [" & objService.DisplayName & "]" & vbNewLine & serviceLog
					end if
				Next
			Next
		end if
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

function StartService(objService)
	dim Result,WaitFor,log
	Result = objService.StartService()

	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = log & objService.DisplayName & " was started successfully." & vbNewLine
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		log = log & "The " & objService.DisplayName & " service is in state " & objService.State & ", Cannot start Service" & vbNewLine
	else
		log = log & objService.DisplayName & " is in state " & objService.State & ", Cannot start Service" & vbNewLine
	end if
	
	StartService = log
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Still does not work..
Manual to auto when manual or disabled does not work
This script that i have does work. Can you please see if this can be got into it.

On Error Resume Next
Dim objFSO, objLog, strLogPath, strLog, strComputerName, intResult, intAttempt, bError, dtStart, dtEnd
 
strLogPath = "\\im\Logs\Service_Logs\"

strLogFile = strLogPath & "ServiceError.txt"
 
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set wshShell = WScript.CreateObject( "WScript.Shell" )
Set objLog = objFSO.OpenTextFile( strLogFile, 8, True)
 
strComputerName = wshShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )
 
dtStart = now()
 
objLog.WriteLine strComputerName & ": Services check start time: " & dtStart
 
for intAttempt = 1 to 3
	bError = False
	For Each procItem in GetObject("winmgmts:").InstancesOf("Win32_Service")
		select case procItem.DisplayName
			case "Sophos Agent","Sophos Anti-Virus","Sophos Anti-Virus status reporter","Sophos AutoUpdate Service","Sophos Device Control Service","Sophos Message Router","Computer Browser","Task Scheduler","Remote Registry","Workstation"
			'case "Alerter"
				err.clear
				if procItem.State = "Stopped" Then
					objLog.WriteLine strComputerName & ": '" & procItem.DisplayName & "' is " & lcase(procItem.State) & "."
					intResult = procItem.StartService()
					if intResult <> 0 then
						objLog.WriteLine strComputerName & ": There was a problem starting the service '" & procItem.DisplayName & "'." & " Attempt #" & intAttempt
						bError = True
					else
						objLog.WriteLine strComputerName & ": The service '" & procItem.DisplayName & "' has been started." & " Attempt #" & intAttempt
					end if
				end if
				err.clear
				if procItem.StartMode <> "Auto" Then
					objLog.WriteLine strComputerName & ": '" & procItem.DisplayName & "' is set to " & lcase(procItem.StartMode) & "."
					intResult = procItem.ChangeStartMode("Automatic")
					if intResult <> 0 then
						objLog.WriteLine strComputerName & ": There was a problem changing the service '" & procItem.DisplayName & "' to start automatically." & " Attempt #" & intAttempt
						bError = True
					else
						objLog.WriteLine strComputerName & ": The service '" & procItem.DisplayName & "' has been changed to start automatically." & " Attempt #" & intAttempt
					end if
				end if
		end select
	Next
	if NOT bError then
		Exit For
	else
		'Pause the script for 5 seconds to before the next pass
		wscript.sleep 5000
	end if
next
 
dtEnd = now()
 
objLog.WriteLine strComputerName & ": Services check total time: " & DateDiff("s",dtStart,dtEnd) & " seconds."

Open in new window

0
 
Meir RivkinFull stack Software EngineerCommented:
it should work, what is the content of services.log ?
0
 
Meir RivkinFull stack Software EngineerCommented:
i think it's because the server is unavailable, and since i removed this log, you can't tell that's the reason.

try run the script on services which are on the local machine.
i've put back the "server is unavailable" log to rule out this case.
post the what services.log output here.
Option Explicit
const SERVICES_LIST = "dfs,DFSR"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

if Trim(logContent) <> "" then
	set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
	objFileLog.Write logContent
	objFileLog.Close

	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

function HandleMachineServices(strComputer)
	machineLog = ""
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
			
			Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service where Name = '" & Trim(strService) & "'")
			
			For Each objService in colListOfServices
				if objService.StartMode <> "Auto" then
					serviceLog = "Change StartMode to Auto" & vbNewLine
					objService.ChangeStartMode("Automatic")
				end if
				
				if objService.State <> "Running" then
					serviceLog = serviceLog & StartService(objService)
				end if
				
				if serviceLog <> "" then
					machineLog = "Service: [" & objService.DisplayName & "]" & vbNewLine & serviceLog
				end if
			Next
		Next
	else
		machineLog = strComputer & " is unavailable"
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

function StartService(objService)
	dim Result,WaitFor,log
	Result = objService.StartService()

	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = log & objService.DisplayName & " was started successfully." & vbNewLine
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		log = log & "The " & objService.DisplayName & " service is in state " & objService.State & ", Cannot start Service" & vbNewLine
	else
		log = log & objService.DisplayName & " is in state " & objService.State & ", Cannot start Service" & vbNewLine
	end if
	
	StartService = log
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Attached are before and after screenshots. The log has this

Machine: [machine 1]
Service: [Sophos Message Router]
Sophos Message Router was started successfully.
0
 
Meir RivkinFull stack Software EngineerCommented:
no screenshots attached.
0
 
Meir RivkinFull stack Software EngineerCommented:
you said  before that in case the service is set to Manual/Disable, the script doesn't change it to Auto.
The 'Sophos Message Router' was set to as Manual before running the script?
0
 
bsharathAuthor Commented:
Please see the screen shots befor and after ones.
Capture1.JPG
Capture2.JPG
0
 
Meir RivkinFull stack Software EngineerCommented:
it seems fine.
try disable the service and stop it, then run the script and see if it changed to Auto and also starting it.
0
 
bsharathAuthor Commented:
You can see in the screen the disabled stopped did not change
Manual stopped also did not change
0
 
Meir RivkinFull stack Software EngineerCommented:
ok, my guess is that there's a dependency between the services, so it's important to know the order to stop them.
did u get anything in the log which indicate that the service could not be started?
0
 
Meir RivkinFull stack Software EngineerCommented:
please ignore my last comment.

did u get anything in the log which indicate that the service could not be started?
or that the service didn't change it's mode?
0
 
bsharathAuthor Commented:
No i did not get anything
When manually start or change it works
0
 
Meir RivkinFull stack Software EngineerCommented:
let me update the script to validate the change after each attempt.
which means that after changing the service mode, i'll query the service again and validate that the mode has really been changed.
same thing with starting the service.
0
 
Meir RivkinFull stack Software EngineerCommented:
ok, i'm pretty sure i covered all options.
crossing my fingers....

Option Explicit
const SERVICES_LIST = "Apache2.2,dfs,DFSR"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

if Trim(logContent) <> "" then
	set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
	objFileLog.Write logContent
	objFileLog.Close

	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

function HandleMachineServices(strComputer)
	machineLog = ""
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")
			
			For Each objService in colListOfServices
				serviceLog = ""
				if objService.StartMode <> "Auto" then
					serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
					objService.ChangeStartMode("Automatic")
				end if
				
				if objService.State <> "Running" then
					if StartService(objService) = true then
						serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
					else
						serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
					end if
				end if
								
				if serviceLog <> "" then
					machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
					machineLog = machineLog & serviceLog
				end if

				exit for
			Next
		Next
	else
		machineLog = strComputer & " is unavailable"
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Sorry still does not work. I get this

No changes are available
But its still the same as shown in the above screenshot
0
 
Meir RivkinFull stack Software EngineerCommented:
what are the names you set to SERVICES_LIST?
0
 
bsharathAuthor Commented:
I think its working fine after changing the service name.
How can i see what its doing. Can i see the checks on the screen?
0
 
bsharathAuthor Commented:
I still get these messages

Machine: [DPC63]
DPC63 is unavailable
0
 
bsharathAuthor Commented:
1. If any one service out of these 6 are not available also i need to log in the email
2. For some machines when all the services are started and automatic also i get this
Sophos Anti-Virus was unable to start.
0
 
Meir RivkinFull stack Software EngineerCommented:
you shouldn't put the display name of the service but the service name.
check the screenshot for example
Untitled.jpg
0
 
bsharathAuthor Commented:
Yes i changed that and it works perfect. Except the above mentioned issues
0
 
Meir RivkinFull stack Software EngineerCommented:
>>If any one service out of these 6 are not available also i need to log in the email
you mean doesn't exists or cannot be run?
0
 
bsharathAuthor Commented:
Doesnt exist
0
 
Meir RivkinFull stack Software EngineerCommented:
now the script should log if service was not found
Option Explicit
const SERVICES_LIST = "Apachde2.2,DFSR"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

if Trim(logContent) <> "" then
	set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
	objFileLog.Write logContent
	objFileLog.Close

	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

function HandleMachineServices(strComputer)
	machineLog = ""
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")

			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & objService.DisplayName & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	else
		machineLog = strComputer & " is unavailable"
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
I dont want to log these
Machine: [DPC63]
DPC63 is unavailable
0
 
Meir RivkinFull stack Software EngineerCommented:
i think you should but no problem.
here it is:

Option Explicit
const SERVICES_LIST = "Apachde2.2,DFSR"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

if Trim(logContent) <> "" then
	set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
	objFileLog.Write logContent
	objFileLog.Close

	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

function HandleMachineServices(strComputer)
	machineLog = ""
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")

			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & objService.DisplayName & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	else
		machineLog = strComputer & " is unavailable"
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
Meir RivkinFull stack Software EngineerCommented:
any progress?
hope i got it right this time.
0
 
bsharathAuthor Commented:
This i am running. Still no completed shall confirm in some time...
0
 
bsharathAuthor Commented:
I have put 1000+ computers and am scanning but its 12hrs and its still running. I guess some issue . Its stuck some where. Can we have another log with machine name and shows whats its doing being logged. So we can check where its getting stuck...
0
 
Meir RivkinFull stack Software EngineerCommented:
sure, i'll have another log called progress_report.log which gonna list each machine and which services already checked.
you should be able to open the log file and see the progress there.
Option Explicit
const SERVICES_LIST = "Apachde2.2,DFSR"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if objFSO.FileExists(LOG_FILE) then
		set objFileLog = objFSO.OpenTextFile(LOG_FILE, 8)
	else
		set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
	end if
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
			objFileLog.Write logContent
		end if
	end if
	
	objFileLog.Close
Next

if Trim(logContent) <> "" then
	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

function HandleMachineServices(strComputer)
	machineLog = ""
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")

			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & objService.DisplayName & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	else
		machineLog = strComputer & " is unavailable"
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
Meir RivkinFull stack Software EngineerCommented:
i've decided to use the same log but to close it on each iteration to allow you to open it and see which server already was processed.
start run the script and every couple of minutes, open the LOG_FILE to see the progress.
0
 
bsharathAuthor Commented:
The script gets stuck at a particular machine. Can we skip that machine and continue
0
 
bsharathAuthor Commented:
I Still get messages as this

Machine: [Dpc2305]
Dpc2305 is unavailable

I want only no services found or what change happened. Not if offline
0
 
Meir RivkinFull stack Software EngineerCommented:
try this:
Option Explicit
const SERVICES_LIST = "Apachde2.2,DFSR"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if objFSO.FileExists(LOG_FILE) then
		set objFileLog = objFSO.OpenTextFile(LOG_FILE, 8)
	else
		set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
	end if
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
			objFileLog.Write logContent
		end if
	end if
	
	objFileLog.Close
Next

if Trim(logContent) <> "" then
	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

function HandleMachineServices(strComputer)
	machineLog = ""
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")

			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & objService.DisplayName & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
If a service is not found i get as this

Machine: [IOF02]
Service: [Sophos Device Control Service] was not found.
Service: [Sophos Device Control Service] was not found.
Service: [Sophos Device Control Service] was not found.
Service: [Sophos Device Control Service] was not found.
Service: [Sophos Device Control Service] was not found.
Service: [Sophos Device Control Service] was not found.

repeated many times
0
 
Meir RivkinFull stack Software EngineerCommented:
hope it's good  now
Option Explicit
const SERVICES_LIST = "XXX"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
	
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

if Trim(logContent) <> "" then
	set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
	objFileLog.Write logContent
	objFileLog.Close

	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

function HandleMachineServices(strComputer)
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
		
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")
			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & strService & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	else
		machineLog = strComputer & " is unavailable"
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Still get the offline report within the email
I dont want the offline details in the email
Just want what it did the changes that it did
0
 
Meir RivkinFull stack Software EngineerCommented:
what do u mean "offline report"?
0
 
bsharathAuthor Commented:
i get email with this content

Machine: [IV01]
IV01 is unavailable
0
 
Meir RivkinFull stack Software EngineerCommented:
ok, i removed all "Unavailable" comments from the log.
Option Explicit
const SERVICES_LIST = "XXX"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
	
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

if Trim(logContent) <> "" then
	set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
	objFileLog.Write logContent
	objFileLog.Close

	NotifyByEmail "Services Email Notification", logContent
	wscript.echo "Complete"
else
	wscript.echo "No change was made to services on all machines."
end if

function HandleMachineServices(strComputer)
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
		
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")
			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & strService & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
ram_process.log
is created on the same folder where i run the script from but its empty
0
 
Meir RivkinFull stack Software EngineerCommented:
i think your last post relate to the other question regarding the machines RAM.
is my last script update works?
0
 
bsharathAuthor Commented:
For a machine where all services are started and automatic but i get this in the email
Its only 6 services but get so many entries for 1 machine

Machine: [SY5652]
Service: [SAVService] was not found.
Service: [Savadminservice] was not found.
Service: [Sophos Device Control Service] was not found.
Service: [Sophos Device Control Service]
Sophos Device Control Service was unable to start.
Service: [Sophos Device Control Service]
Sophos Device Control Service was unable to start.
Service: [Sophos Device Control Service]
Sophos Device Control Service was unable to start.
Service: [Sophos Device Control Service]
Sophos Device Control Service was unable to start.
Service: [Sophos Device Control Service]
Sophos Device Control Service was unable to start.
Service: [Sophos Device Control Service]
Sophos Device Control Service was unable to start.
Service: [Sophos Device Control Service]
Sophos Device Control Service was unable to start.
Service: [Sophos Device Control Service]
Sophos Device Control Service was unable to start.
Service: [Sophos Device Control Service]
Change StartMode to Auto
Sophos Device Control Service was started successfully.
Service: [Sophos Message Router]
Sophos Message Router was started successfully.
Service: [Sophos Device Control Service] was not found.
Service: [Sophos Device Control Service] was not found.
Service: [Sophos Anti-Virus]
Sophos Anti-Virus was unable to start.
Service: [Sophos Device Control Service]
Sophos Device Control Service was unable to start.
0
 
Meir RivkinFull stack Software EngineerCommented:
i overwrite the log file anyway so you shouldn't get duplicate messages.
Option Explicit
const SERVICES_LIST = "Apache2.2"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
	
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

if Trim(logContent) <> "" then
	objFileLog.Write logContent
	NotifyByEmail "Services Email Notification", logContent
else
	objFileLog.Write "No change was made to services on all machines."
end if

objFileLog.Close
wscript.echo "Complete"
	
function HandleMachineServices(strComputer)
	if Ping(strComputer) = true then
		on error resume next
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
		
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")
			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & strService & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
But some machines details in the email i get not found even if the services are available.
And a machine where the services are started shows as not started.
and if a service is not available thats hown more than 5 times in the email
0
 
Meir RivkinFull stack Software EngineerCommented:
found the bug in the log file, please test the script.
Option Explicit
const SERVICES_LIST = "Apache2.2,wuauserv"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
	
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

if Trim(logContent) <> "" then
	objFileLog.Write logContent
	NotifyByEmail "Services Email Notification", logContent
else
	objFileLog.Write "No change was made to services on all machines."
end if

objFileLog.Close
wscript.echo "Complete"
	
function HandleMachineServices(strComputer)
	if Ping(strComputer) = true then
		on error resume next
		machineLog = ""
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
		
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")
			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & strService & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	Set myRecipient = ns.CreateRecipient(ToAddress)
	myRecipient.Resolve
	If Not myRecipient.Resolved Then
	   MsgBox "unknown recipient"
	Else
	   newMail.Recipients.Add(myRecipient)
	   newMail.Send
	End If

	Set ol = Nothing

end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Hi now everything is fine.
I want to add more than 1 email address in To. I get unknow error when i add additional users
I want 2 segments in the mail one portion all failures and another all success that the script turned ON. can this be done please...
0
 
Meir RivkinFull stack Software EngineerCommented:
thank god, took me a while to find this bug...

om terms of having multiple recipients, can u check it with comma separated or semicolon separated?

should be either:

ToAddress = "xxx.yyy@zzz.com;123@345.com"
      
or

ToAddress = "xxx.yyy@zzz.com,123@345.com"

once you give me ok on this issue i'll take care of your 2nd requirement.
0
 
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
@Sedgwick

  I just want to give You "Mad Props" (to use that comical parlance from the late 90s) with all the time and effort you have put in on this question.

  You're a really dedicated EE-er and this question has been a nightmare, I can tell as I've been following it. Not only have you dealt with multiple expantions of the requirements, but you've hsd to deal with new crops of bugs at every turn and still you're persevering for a measly 500 points.

  I just wanted to say, I don't think I could have survived this long, and you sir have my respect and admiration for sticking it out with so little recognition.  I am rooting For you silently from the side-lines!  I'm glad to see this nighgtmare of a Question may nearly be surmounted!  My hats off to you!


~Q
0
 
Meir RivkinFull stack Software EngineerCommented:
@QCubed

thank you for your warm words, best of luck :)
0
 
bsharathAuthor Commented:
QCubed yes i agree with you 100% the kind of patience sedgwick has is great... He has helped me in sooo many posts.. thank you... :-)

sedgwick i get the below error and the emails are still unknown
---------------------------
Windows Script Host
---------------------------
Script:      D:\Run_Via_ScheduleTask\Services start and email.vbs
Line:      26
Char:      1
Error:      Permission denied
Code:      800A0046
Source:       Microsoft VBScript runtime error

---------------------------
OK  
---------------------------
0
 
Meir RivkinFull stack Software EngineerCommented:
did it happen after you add multiple recipients in the email function?
can u post the line in your script which triggers the error?
0
 
bsharathAuthor Commented:
yes after i add i got this

---------------------------

---------------------------
unknown recipient
---------------------------
OK  
---------------------------

There is only the above error

The below code was given by you. even this had the same issue. later rob helped me solve it. can you see if this gives an idea please...
const SCHEDULER_TASK_NAME = "PcsEnumTask"
const SCHEDULER_TASK_START_TIME = "12:00:00"
const ROOT_OU = "OU=Ia,OU=Offices,"

Dim bChange
dim LogResult,args
Dim objShell : Set objShell = CreateObject("WScript.Shell")
Dim strOutput : strOutput = objShell.Exec("schtasks /query /fo list").StdOut.ReadAll

if InStr(data, SCHEDULER_TASK_NAME) = 0 then
        'WScript.Echo SCHEDULER_TASK_NAME & " found.."
end if

if InStr(strOutput, SCHEDULER_TASK_NAME) = 0 then
''        WScript.Echo "Create task scheduler [" & SCHEDULER_TASK_NAME & "]..."
        'create task scheduler
        args = "schtasks /Create /F /SC DAILY /TN " & SCHEDULER_TASK_NAME & " /TR """ & Wscript.ScriptFullName & """ /ST " & SCHEDULER_TASK_START_TIME
		'WScript.Echo "args: " & args
		objShell.Run args, 1, True

        'WScript.Echo "Task scheduler [" & SCHEDULER_TASK_NAME & "] created successfully"
Else
		bChange = False
        'numertae pcs and email
        EnumPcs
		EnumGroups
		EnumUsers
        If bChange = True Then EmailResult
end if

Sub EmailResult
dim ToAddress,MessageSubject,MessageBody

ToAddress = "sha@plc.com;shar@plc.com"


	MessageSubject = "Newly created objects today..."

MessageBody = LogResult 

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	newMail.to = ToAddress
         If Not newmail.Recipients.ResolveAll Then
             For Each myRecipient In myRecipients
                 If Not myRecipient.Resolved Then
                     MsgBox myRecipient.Name & " is unknown"
                 End If
              Next
          Else
               newMail.Send
          End If

Set ol = Nothing


End Sub

Sub EnumUsers
	LogResult = LogResult & vbNewLine & "Users Report:"  & vbNewLine
	dtmDate = Now
         
        strYear = Right(Year(dtmDate), 2)
        strMonth = Month(dtmDate)
        If Len(strMonth) < 2 Then strMonth = "0" & strMonth
        strDay = Day(dtmDate)
        If Len(strDay) < 2 Then strDay = "0" & strDay
         
        strStartDate = strYear & strMonth & strDay & "000000Z"
        strEndDate = strYear & strMonth & strDay & "235959Z"
         
        strFilter = "(&(createTimeStamp>=" & strStartDate & ")(createTimeStamp<=" & strEndDate & ")(objectCategory=user))"

        Set objConnection = CreateObject("ADODB.Connection")
        objConnection.Provider = "ADsDSOObject"
        objConnection.Open "Active Directory Provider"
         
        Set objRootDSE = GetObject("LDAP://RootDSE")
        Set objRecordSet = objConnection.Execute( _
          "<LDAP://" & ROOT_OU & objRootDSE.Get("defaultNamingContext") & ">;" & _
          strFilter & ";name,createTimeStamp;subtree")
        Set objRootDSE = Nothing
         
        While Not objRecordSet.EOF
          dtmCreateTimeStamp = CDate(objRecordSet.Fields("createTimeStamp").Value)
          strMessage = objRecordSet.Fields("name") & " " & _
                objRecordSet.Fields("createTimeStamp")
         
          LogResult = LogResult & strMessage & VbCrLf 
          bChange = True
          objRecordSet.MoveNext
        WEnd
end sub

Sub EnumGroups
LogResult = LogResult & vbNewLine & "Groups Report:"  & vbNewLine

	dtmDate = Now
         
        strYear = Right(Year(dtmDate), 2)
        strMonth = Month(dtmDate)
        If Len(strMonth) < 2 Then strMonth = "0" & strMonth
        strDay = Day(dtmDate)
        If Len(strDay) < 2 Then strDay = "0" & strDay
         
        strStartDate = strYear & strMonth & strDay & "000000Z"
        strEndDate = strYear & strMonth & strDay & "235959Z"
         
        strFilter = "(&(createTimeStamp>=" & strStartDate & ")(createTimeStamp<=" & strEndDate & ")(objectCategory=group))"

        Set objConnection = CreateObject("ADODB.Connection")
        objConnection.Provider = "ADsDSOObject"
        objConnection.Open "Active Directory Provider"
         
        Set objRootDSE = GetObject("LDAP://RootDSE")
        Set objRecordSet = objConnection.Execute( _
          "<LDAP://" & ROOT_OU & objRootDSE.Get("defaultNamingContext") & ">;" & _
          strFilter & ";name,createTimeStamp;subtree")
        Set objRootDSE = Nothing
         
        While Not objRecordSet.EOF
          dtmCreateTimeStamp = CDate(objRecordSet.Fields("createTimeStamp").Value)
          strMessage = objRecordSet.Fields("name") & " " & _
                objRecordSet.Fields("createTimeStamp")
         
          LogResult = LogResult & strMessage & VbCrLf 
          bChange = True
          objRecordSet.MoveNext
        WEnd

end sub

Sub EnumPcs

LogResult = LogResult & vbNewLine & "Pcs Report:"  & vbNewLine
        dtmDate = Now
         
        strYear = Right(Year(dtmDate), 2)
        strMonth = Month(dtmDate)
        If Len(strMonth) < 2 Then strMonth = "0" & strMonth
        strDay = Day(dtmDate)
        If Len(strDay) < 2 Then strDay = "0" & strDay
         
        strStartDate = strYear & strMonth & strDay & "000000Z"
        strEndDate = strYear & strMonth & strDay & "235959Z"
         
        strFilter = "(&(createTimeStamp>=" & strStartDate & ")(createTimeStamp<=" & strEndDate & ")(objectCategory=computer))"

        Set objConnection = CreateObject("ADODB.Connection")
        objConnection.Provider = "ADsDSOObject"
        objConnection.Open "Active Directory Provider"
         
        Set objRootDSE = GetObject("LDAP://RootDSE")
        Set objRecordSet = objConnection.Execute( _
          "<LDAP://" & ROOT_OU & objRootDSE.Get("defaultNamingContext") & ">;" & _
          strFilter & ";name,createTimeStamp;subtree")
        Set objRootDSE = Nothing
         
        While Not objRecordSet.EOF
          dtmCreateTimeStamp = CDate(objRecordSet.Fields("createTimeStamp").Value)
          strMessage = objRecordSet.Fields("name") & " " & _
                objRecordSet.Fields("createTimeStamp")
         
          LogResult = LogResult & strMessage & VbCrLf 
          bChange = True
          objRecordSet.MoveNext
        WEnd

End Sub

Open in new window

0
 
bsharathAuthor Commented:
I get this error alos

---------------------------
Windows Script Host
---------------------------
Script:      D:\Run_Via_ScheduleTask\Services start and email.vbs
Line:      26
Char:      1
Error:      Permission denied
Code:      800A0046
Source:       Microsoft VBScript runtime error

---------------------------
OK  
---------------------------
0
 
Meir RivkinFull stack Software EngineerCommented:
did u check both options in the recipients list?
i can't remember if you divide them with comma separator or semi-colon separator.
0
 
Meir RivkinFull stack Software EngineerCommented:
can u post the actual line 26?
0
 
bsharathAuthor Commented:
Line 26 has this
set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)
0
 
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
Put a fuLl path to the log file, and surround it by quotes, see if that fixes it.
0
 
Meir RivkinFull stack Software EngineerCommented:
this error happens in relate to the recipients list problem.
my guess is that the error encounter in the recipients list stop the script before closing the log file on line 34.
to overcome this problem open task manager and kill wscript instances.

i read that a comma should be used to divide recipients so use that.
let me know if you still got problem sending the email to multiple recipients.
0
 
Meir RivkinFull stack Software EngineerCommented:
so instead of:
ToAddress = "sha@plc.com;shar@plc.com"

use:
ToAddress = "sha@plc.com,shar@plc.com"
0
 
bsharathAuthor Commented:
Still get as unknow
0
 
Meir RivkinFull stack Software EngineerCommented:
here
const SCHEDULER_TASK_NAME = "PcsEnumTask"
const SCHEDULER_TASK_START_TIME = "12:00:00"
const ROOT_OU = "OU=Ia,OU=Offices,"

Dim bChange
dim LogResult,args
Dim objShell : Set objShell = CreateObject("WScript.Shell")
Dim strOutput : strOutput = objShell.Exec("schtasks /query /fo list").StdOut.ReadAll

if InStr(data, SCHEDULER_TASK_NAME) = 0 then
        'WScript.Echo SCHEDULER_TASK_NAME & " found.."
end if

if InStr(strOutput, SCHEDULER_TASK_NAME) = 0 then
''        WScript.Echo "Create task scheduler [" & SCHEDULER_TASK_NAME & "]..."
        'create task scheduler
        args = "schtasks /Create /F /SC DAILY /TN " & SCHEDULER_TASK_NAME & " /TR """ & Wscript.ScriptFullName & """ /ST " & SCHEDULER_TASK_START_TIME
		'WScript.Echo "args: " & args
		objShell.Run args, 1, True

        'WScript.Echo "Task scheduler [" & SCHEDULER_TASK_NAME & "] created successfully"
Else
		bChange = False
        'numertae pcs and email
        EnumPcs
		EnumGroups
		EnumUsers
        If bChange = True Then EmailResult
end if

Sub EmailResult
dim ToAddress,MessageSubject,MessageBody,recipient

ToAddress = "sha@plc.com;shar@plc.com"


	MessageSubject = "Newly created objects today..."

MessageBody = LogResult 

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	for each recipient in Split(ToAddress,";")
        Set myRecipient = ns.CreateRecipient(recipient)
        myRecipient.Resolve
        If Not myRecipient.Resolved Then
           MsgBox "unknown recipient"
        Else
           newMail.Recipients.Add(myRecipient)           
        End If
    next
    
    newMail.Send
    Set ol = Nothing



End Sub

Sub EnumUsers
	LogResult = LogResult & vbNewLine & "Users Report:"  & vbNewLine
	dtmDate = Now
         
        strYear = Right(Year(dtmDate), 2)
        strMonth = Month(dtmDate)
        If Len(strMonth) < 2 Then strMonth = "0" & strMonth
        strDay = Day(dtmDate)
        If Len(strDay) < 2 Then strDay = "0" & strDay
         
        strStartDate = strYear & strMonth & strDay & "000000Z"
        strEndDate = strYear & strMonth & strDay & "235959Z"
         
        strFilter = "(&(createTimeStamp>=" & strStartDate & ")(createTimeStamp<=" & strEndDate & ")(objectCategory=user))"

        Set objConnection = CreateObject("ADODB.Connection")
        objConnection.Provider = "ADsDSOObject"
        objConnection.Open "Active Directory Provider"
         
        Set objRootDSE = GetObject("LDAP://RootDSE")
        Set objRecordSet = objConnection.Execute( _
          "<LDAP://" & ROOT_OU & objRootDSE.Get("defaultNamingContext") & ">;" & _
          strFilter & ";name,createTimeStamp;subtree")
        Set objRootDSE = Nothing
         
        While Not objRecordSet.EOF
          dtmCreateTimeStamp = CDate(objRecordSet.Fields("createTimeStamp").Value)
          strMessage = objRecordSet.Fields("name") & " " & _
                objRecordSet.Fields("createTimeStamp")
         
          LogResult = LogResult & strMessage & VbCrLf 
          bChange = True
          objRecordSet.MoveNext
        WEnd
end sub

Sub EnumGroups
LogResult = LogResult & vbNewLine & "Groups Report:"  & vbNewLine

	dtmDate = Now
         
        strYear = Right(Year(dtmDate), 2)
        strMonth = Month(dtmDate)
        If Len(strMonth) < 2 Then strMonth = "0" & strMonth
        strDay = Day(dtmDate)
        If Len(strDay) < 2 Then strDay = "0" & strDay
         
        strStartDate = strYear & strMonth & strDay & "000000Z"
        strEndDate = strYear & strMonth & strDay & "235959Z"
         
        strFilter = "(&(createTimeStamp>=" & strStartDate & ")(createTimeStamp<=" & strEndDate & ")(objectCategory=group))"

        Set objConnection = CreateObject("ADODB.Connection")
        objConnection.Provider = "ADsDSOObject"
        objConnection.Open "Active Directory Provider"
         
        Set objRootDSE = GetObject("LDAP://RootDSE")
        Set objRecordSet = objConnection.Execute( _
          "<LDAP://" & ROOT_OU & objRootDSE.Get("defaultNamingContext") & ">;" & _
          strFilter & ";name,createTimeStamp;subtree")
        Set objRootDSE = Nothing
         
        While Not objRecordSet.EOF
          dtmCreateTimeStamp = CDate(objRecordSet.Fields("createTimeStamp").Value)
          strMessage = objRecordSet.Fields("name") & " " & _
                objRecordSet.Fields("createTimeStamp")
         
          LogResult = LogResult & strMessage & VbCrLf 
          bChange = True
          objRecordSet.MoveNext
        WEnd

end sub

Sub EnumPcs

LogResult = LogResult & vbNewLine & "Pcs Report:"  & vbNewLine
        dtmDate = Now
         
        strYear = Right(Year(dtmDate), 2)
        strMonth = Month(dtmDate)
        If Len(strMonth) < 2 Then strMonth = "0" & strMonth
        strDay = Day(dtmDate)
        If Len(strDay) < 2 Then strDay = "0" & strDay
         
        strStartDate = strYear & strMonth & strDay & "000000Z"
        strEndDate = strYear & strMonth & strDay & "235959Z"
         
        strFilter = "(&(createTimeStamp>=" & strStartDate & ")(createTimeStamp<=" & strEndDate & ")(objectCategory=computer))"

        Set objConnection = CreateObject("ADODB.Connection")
        objConnection.Provider = "ADsDSOObject"
        objConnection.Open "Active Directory Provider"
         
        Set objRootDSE = GetObject("LDAP://RootDSE")
        Set objRecordSet = objConnection.Execute( _
          "<LDAP://" & ROOT_OU & objRootDSE.Get("defaultNamingContext") & ">;" & _
          strFilter & ";name,createTimeStamp;subtree")
        Set objRootDSE = Nothing
         
        While Not objRecordSet.EOF
          dtmCreateTimeStamp = CDate(objRecordSet.Fields("createTimeStamp").Value)
          strMessage = objRecordSet.Fields("name") & " " & _
                objRecordSet.Fields("createTimeStamp")
         
          LogResult = LogResult & strMessage & VbCrLf 
          bChange = True
          objRecordSet.MoveNext
        WEnd

End Sub

Open in new window

0
 
bsharathAuthor Commented:
Hi,

is the last code for services post ?
0
 
Meir RivkinFull stack Software EngineerCommented:
i took it from your last post and added the changes
0
 
bsharathAuthor Commented:
Why is this line in
const ROOT_OU = "OU=Ia,OU=Offices,"

i will query a txt file for computer names
I dont want a schedule created
0
 
Meir RivkinFull stack Software EngineerCommented:
this is what you posted on ID: 33763325 (your last post with code)
0
 
bsharathAuthor Commented:
I posted that just for your reference stating. even that code was given by you and had the same emailing issue to more than 1 person. later i posted a Q and another expert sorted the emailing issue. If you can check that code and take the emailing option into your code thats for the services emailing.
then this would solve our issue
0
 
Meir RivkinFull stack Software EngineerCommented:
i lost track of the code revisions posted here.
i took the last code I have posted ID:33710678, and add the email fix which support multiple recipients.

Option Explicit
const SERVICES_LIST = "Apache2.2,wuauserv"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
	
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

if Trim(logContent) <> "" then
	objFileLog.Write logContent
	NotifyByEmail "Services Email Notification", logContent
else
	objFileLog.Write "No change was made to services on all machines."
end if

objFileLog.Close
wscript.echo "Complete"
	
function HandleMachineServices(strComputer)
	if Ping(strComputer) = true then
		on error resume next
		machineLog = ""
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
		
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")
			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & strService & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	for each recipient in Split(ToAddress,";")
        Set myRecipient = ns.CreateRecipient(recipient)
        myRecipient.Resolve
        If Not myRecipient.Resolved Then
           MsgBox "unknown recipient"
        Else
           newMail.Recipients.Add(myRecipient)           
        End If
    next


end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
I get this

---------------------------
Windows Script Host
---------------------------
Script:      D:\Run\Services start and email.vbs
Line:      98
Char:      2
Error:      Variable is undefined: 'recipient'
Code:      800A01F4
Source:       Microsoft VBScript runtime error

---------------------------
OK  
---------------------------
0
 
Meir RivkinFull stack Software EngineerCommented:
fixed
Option Explicit
const SERVICES_LIST = "Apache2.2,wuauserv"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
	
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

if Trim(logContent) <> "" then
	objFileLog.Write logContent
	NotifyByEmail "Services Email Notification", logContent
else
	objFileLog.Write "No change was made to services on all machines."
end if

objFileLog.Close
wscript.echo "Complete"
	
function HandleMachineServices(strComputer)
	if Ping(strComputer) = true then
		on error resume next
		machineLog = ""
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
		
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")
			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & strService & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
dim recipient 
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	for each recipient in Split(ToAddress,";")
        Set myRecipient = ns.CreateRecipient(recipient)
        myRecipient.Resolve
        If Not myRecipient.Resolved Then
           MsgBox "unknown recipient"
        Else
           newMail.Recipients.Add(myRecipient)           
        End If
    next


end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Still get unknown receiptiant error
0
 
Meir RivkinFull stack Software EngineerCommented:
try now
Option Explicit
const SERVICES_LIST = "Apache2.2,wuauserv"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
	
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

if Trim(logContent) <> "" then
	objFileLog.Write logContent
	NotifyByEmail "Services Email Notification", logContent
else
	objFileLog.Write "No change was made to services on all machines."
end if

objFileLog.Close
wscript.echo "Complete"
	
function HandleMachineServices(strComputer)
	if Ping(strComputer) = true then
		on error resume next
		machineLog = ""
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
		
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")
			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & strService & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
dim recipient 
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	for each recipient in Split(ToAddress,";")
        Set myRecipient = ns.CreateRecipient(recipient)
        myRecipient.Resolve
        If Not myRecipient.Resolved Then
           MsgBox "unknown recipient"
        Else
           newMail.Recipients.Add(myRecipient)           
        End If
    next


end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Still get the same message
0
 
Meir RivkinFull stack Software EngineerCommented:
try now
const SERVICES_LIST = "Apache2.2,wuauserv"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
	
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

if Trim(logContent) <> "" then
	objFileLog.Write logContent
	NotifyByEmail "Services Email Notification", logContent
else
	objFileLog.Write "No change was made to services on all machines."
end if

objFileLog.Close
wscript.echo "Complete"
	
function HandleMachineServices(strComputer)
	if Ping(strComputer) = true then
		on error resume next
		machineLog = ""
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
		
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")
			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & strService & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
dim recipient 
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	for each recipient in Split(ToAddress,";")
        Set myRecipient = ns.CreateRecipient(recipient)
        myRecipient.Resolve
        If Not myRecipient.Resolved Then
           MsgBox "unknown recipient"
        Else
           newMail.Recipients.Add(myRecipient)           
        End If
    next


end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Still same message
0
 
Meir RivkinFull stack Software EngineerCommented:
i don't understand, is still on recipient on line 98?
0
 
bsharathAuthor Commented:
No i have 2

shar@plc.com;Sha@plc.com
0
 
Meir RivkinFull stack Software EngineerCommented:
sorry, what is the message exactly?
0
 
bsharathAuthor Commented:
I get this

---------------------------

---------------------------
unknown recipient
---------------------------
OK  
---------------------------

I have the line as this

      ToAddress = "sha.plc.com;fsr@plc.com"
0
 
Meir RivkinFull stack Software EngineerCommented:
i've added a validation on recipient, try now:
const SERVICES_LIST = "Apache2.2,wuauserv"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
	
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

if Trim(logContent) <> "" then
	objFileLog.Write logContent
	NotifyByEmail "Services Email Notification", logContent
else
	objFileLog.Write "No change was made to services on all machines."
end if

objFileLog.Close
wscript.echo "Complete"
	
function HandleMachineServices(strComputer)
	if Ping(strComputer) = true then
		on error resume next
		machineLog = ""
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
		
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")
			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & strService & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
dim recipient 
	Dim ToAddress
	Dim MessageSubject
	Dim MessageBody
	Dim MessageAttachment
	dim myRecipient,olMailItem

	Dim ol, ns, newMail

	ToAddress = "xxx.yyy@zzz.com"
	MessageSubject = strSubject
	MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	' validate the recipient, just in case...
	for each recipient in Split(ToAddress,";")
if Trim(recipient) <> "" then
        Set myRecipient = ns.CreateRecipient(recipient)
        myRecipient.Resolve
        If Not myRecipient.Resolved Then
           MsgBox "unknown recipient"
        Else
           newMail.Recipients.Add(myRecipient)           
        End If
end if
    next


end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Still get
---------------------------

---------------------------
unknown recipient
---------------------------
OK  
---------------------------
0
 
Meir RivkinFull stack Software EngineerCommented:
what line number?
0
 
Meir RivkinFull stack Software EngineerCommented:
of course, it is the message box from line 103.
its not an error.

if the recipient was not validated by MAPI then you see this message.
in that case it depends what you wish to do when recipient is not resolved.
you could either ignore and simply log an error in the log file or abort the script.
0
 
bsharathAuthor Commented:
But there is no chance of it not resolving. As other scripts use the same email addesses.
0
 
Meir RivkinFull stack Software EngineerCommented:
>>As other scripts use the same email addresses.
how the other scripts send the email?
0
 
bsharathAuthor Commented:
They use the logged in user outlook to email. As the other code that is in the Q . That code works
ID: 33763325
0
 
Meir RivkinFull stack Software EngineerCommented:
i took the email part from the previous code posted (33763325), is it working for you?
const SERVICES_LIST = "Apache2.2,wuauserv"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
	
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

if Trim(logContent) <> "" then
	objFileLog.Write logContent
	NotifyByEmail "Services Email Notification", logContent
else
	objFileLog.Write "No change was made to services on all machines."
end if

objFileLog.Close
wscript.echo "Complete"
	
function HandleMachineServices(strComputer)
	if Ping(strComputer) = true then
		on error resume next
		machineLog = ""
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
		
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")
			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & strService & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
dim ToAddress,MessageSubject,MessageBody

ToAddress = "sha@plc.com;shar@plc.com"

MessageSubject = strSubject
MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	newMail.to = ToAddress
         If Not newmail.Recipients.ResolveAll Then
             For Each myRecipient In myRecipients
                 If Not myRecipient.Resolved Then
                     MsgBox myRecipient.Name & " is unknown"
                 End If
              Next
          Else
               newMail.Send
          End If

Set ol = Nothing


end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
I get this

---------------------------
Windows Script Host
---------------------------
Script:      D:\Run_Via_ScheduleTask\Services start and email.vbs
Line:      85
Char:      2
Error:      Variable is undefined: 'ol'
Code:      800A01F4
Source:       Microsoft VBScript runtime error

---------------------------
OK  
---------------------------
0
 
Meir RivkinFull stack Software EngineerCommented:
try now
const SERVICES_LIST = "Apache2.2,wuauserv"
const MACHINES_LIST_FILE = "c:\temp\machines.txt"
const LOG_FILE = "c:\temp\services.log"

dim objFileLog,objFSO,objFile,logResult,logContent,strService,serviceLog,machineLog
Dim objWMIService, objItem, objService, strServiceList
Dim service,arrMachines, colListOfServices, strComputer, strQuery
 
set objFSO = createobject("scripting.filesystemobject")
set objFile = objFSO.OpenTextFile(MACHINES_LIST_FILE, 1)
arrMachines = Split(objFile.ReadAll, vbNewLine)
objFile.Close

for each strComputer in arrMachines
	if Trim(strComputer) <> "" then
		logResult = HandleMachineServices(strComputer)
	
		if logResult <> "" then
			logContent = logContent & "Machine: [" & strComputer & "]" & vbNewLine & logResult & vbNewLine
		end if
	end if
Next

set objFileLog = objFSO.CreateTextFile(LOG_FILE, 2)

if Trim(logContent) <> "" then
	objFileLog.Write logContent
	NotifyByEmail "Services Email Notification", logContent
else
	objFileLog.Write "No change was made to services on all machines."
end if

objFileLog.Close
wscript.echo "Complete"
	
function HandleMachineServices(strComputer)
	if Ping(strComputer) = true then
		on error resume next
		machineLog = ""
		Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
		for each strService in Split(SERVICES_LIST, ",")
		
			Set colListOfServices = objWMIService.ExecQuery("Select StartMode,State,DisplayName from Win32_Service where Name = '" & Trim(strService) & "'")
			if colListOfServices.Count = 0 then
				machineLog = machineLog & "Service: [" & strService & "] was not found." & vbNewLine
			else
				For Each objService in colListOfServices
					serviceLog = ""
					if objService.StartMode <> "Auto" then
						serviceLog = serviceLog & "Change StartMode to Auto" & vbNewLine
						objService.ChangeStartMode("Automatic")
					end if
					
					if objService.State <> "Running" then
						if StartService(objService) = true then
							serviceLog = serviceLog & objService.DisplayName & " was started successfully." & vbNewLine
						else
							serviceLog = serviceLog & objService.DisplayName & " was unable to start." & vbNewLine
						end if
					end if
									
					if serviceLog <> "" then
						machineLog = machineLog & "Service: [" & objService.DisplayName & "]" & vbNewLine
						machineLog = machineLog & serviceLog
					end if

					exit for
				Next
			end if
		Next
	end if
	
	HandleMachineServices = machineLog
end function

sub NotifyByEmail(strSubject, strResult)
dim ToAddress,MessageSubject,MessageBody
Dim ol, ns, newMail

ToAddress = "sha@plc.com;shar@plc.com"

MessageSubject = strSubject
MessageBody = strResult

	Set ol = WScript.CreateObject("Outlook.Application")
	Set ns = ol.getNamespace("MAPI")
	ns.logon "","",true,false
	Set newMail = ol.CreateItem(olMailItem)
	newMail.Subject = MessageSubject
	newMail.Body = MessageBody & vbCrLf

	newMail.to = ToAddress
         If Not newmail.Recipients.ResolveAll Then
             For Each myRecipient In myRecipients
                 If Not myRecipient.Resolved Then
                     MsgBox myRecipient.Name & " is unknown"
                 End If
              Next
          Else
               newMail.Send
          End If

Set ol = Nothing


end sub

function StartService(objService)
	dim Result,WaitFor
	Result = objService.StartService()
		
	if Result = 0 then
		WaitFor = 10000 '10 seconds
		while WaitFor > 0
			WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
			set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
			if objService.State = "Running" then
				StartService = true
				exit function
			end if
		wend
	
		set objService = objWMIService.Get("Win32_Service.Name='" & objService.Name & "'")
		if objService.State = "Running" then
			StartService = true
			exit function
		else
			StartService = false
			exit function

		end if
	end if
	
	StartService = false
end function

Function Ping(strHost)

    dim objPing, objRetStatus

    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")

    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
			Ping = False
        else
            Ping = True
        end if
    next
End Function

Open in new window

0
 
bsharathAuthor Commented:
Thanks a long for such patient help was great help
0
 
Meir RivkinFull stack Software EngineerCommented:
anytime :)
0
 
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
Congratulations Sedgwick, I want to nominate you for some sort of award, you went above and beyond on this one Ten Fold!
0
 
Meir RivkinFull stack Software EngineerCommented:
QCubed: that won't be necessary, my award is the satisfaction of having able to help others and share my knowledge with others.
0

Featured Post

Microsoft Certification Exam 74-409

VeeamĀ® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

  • 65
  • 53
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now