Reputation: 13
Please need help. My script is
Set objService = GetObject("winmgmts:\\.\Root\CIMV2")
Set colListOfServices = objService.ExecQuery _
("Select * from Win32_Service Where StartMode = 'Auto'
AND Started = false")
For Each objService in colListOfServices
WScript.Echo Date & " " & Time & objService.Caption
Set xmlDoc = _
CreateObject("Microsoft.XMLDOM")
XMLDoc.async = False
Set objRoot = _
xmlDoc.createElement("ServerCheck")
xmlDoc.appendChild objRoot
Set objRecord = _
xmlDoc.createElement("Services")
objRoot.appendChild objRecord
For Each objName in colListOfServices
Set objName = _
xmlDoc.createElement("Name")
objName.Text = objService.Caption
objRecord.appendChild objName
Next
Set objDate = _
xmlDoc.createElement("Date")
objDate.Text = Date & Time
objRecord.appendChild objDate
Set objIntro = _
xmlDoc.createProcessingInstruction _
("xml","version='1.0'")
xmlDoc.insertBefore _
objIntro,xmlDoc.childNodes(0)
xmlDoc.Save "C:\Users\111\Desktop\Audits.xml"
Next
And my XML
Services><Name>Windows install</Name><Name>Windows install</Name>
<Name>Windows install</Name><Date>25.12.201215:51:19</Date>
WScript.Echo(to test) give me 3 different stopped serveces. But in my XML save only one service in 3 copys. How can I save in XML all stopped services right?
Upvotes: 1
Views: 624
Reputation: 338158
I want that my script write in XML all stopped services in Auto start mode.
Your problem is that you create and write a new XML file within the For Each
loop. You keep overwriting the same file again and again, ending up with a file that contains the last stopped service only.
Create and save the XML outside of the loop.
Option Explicit
Dim objWmi, wql, objService, xmlDoc, objRoot, objRecord
Set objWmi = GetObject("winmgmts:\\.\Root\CIMV2")
wql = "SELECT * FROM Win32_Service WHERE StartMode = 'Auto' AND Started = false"
Set xmlDoc = CreateObject("MSXML2.DOMDocument")
xmlDoc.async = False
Set objRoot = NewElement(xmlDoc, "ServerCheck", "")
For Each objService in objWmi.ExecQuery(wql)
WScript.Echo Date & " " & Time & objService.Caption
Set objRecord = NewElement(objRoot, "Services", "")
NewElement objRecord, "Name", objService.Caption
NewElement objRecord, "Date", Date & " " & Time
Next
xmlDoc.Save "C:\Users\111\Desktop\Audits.xml"
' --------------------------------------------------------------------
Function NewElement(parent, name, text)
Set NewElement = parent.ownerDocument.createElement(name)
If text <> "" Then NewElement.Text = text
parent.appendChild NewElement
End Function
I've made a few other improvements, too.
Upvotes: 1