I am trying to retrieve all processes running on a machine with the usual information; process id, name and the memory usage. im trying to export it all under one xml file, however to get all the information i had to use 2 separate methods.
to get the process id, name and session id (process owner) i used the following code along with a dictionary and a class, usng a .net library called Cassia.
Using server As ITerminalServer = manager.GetRemoteServer("Spartacus")
server.Open()
For Each process As ITerminalServicesProcess In server.GetProcesses()
If Not String.IsNullOrEmpty(process.ProcessId) Then
dictprocess.Add(process.ProcessId, New Processes(process.ProcessId, process.ProcessName, process.SessionId))
End If
Next
End Using
Dim sbProcess As New StringBuilder
sbProcess.AppendLine("<?xml version=""1.0""?>")
sbProcess.AppendLine("<Processes>")
For Each item As KeyValuePair(Of Integer, Processes) In dictprocess
sbProcess.AppendFormat("<Name>""{0}""<ProcessID>""{1}""</ProcessID><ProcessName>{2}</ProcessName><SessionID>{3}</SessionID></Name>", item.Key, item.Value.ProcessId, item.Value.ProcessName, item.Value.SessionId).AppendLine()
Next
sbProcess.AppendLine("</Processes>")
in order to get the memory and page file usage i used a wmi query
Dim sbTest As New System.Text.StringBuilder
objWMI = GetObject("winmgmts:\\.\root\cimv2")
colObjects = objWMI.ExecQuery("Select * From Win32_Process")
For Each Item In colObjects
sbTest.AppendFormat("<ProcessID>""{0}""<ProcessName>""{1}""</ProcessName><MemoryUsage>{2}</MemoryUsage><PageFileUsage>{3}</PageFileUsage></ProcessID>", Item.ProcessID, Item.Name, (Item.WorkingSetSize / 1024), Item.PageFileUsage)
Next
I can write the results as two separate xml files:
Process id, name and session id:
- <Processes>
- <Name>
"540"
<ProcessID>"540"</ProcessID>
<ProcessName>wininit.exe</ProcessName>
<SessionID>0</SessionID>
</Name>
- <Name>
"552"
<ProcessID>"552"</ProcessID>
<ProcessName>csrss.exe</ProcessName>
<SessionID>1</SessionID>
Process memory and page file usage
- <ProcessUsage>
- <ProcessID>
"540"
<ProcessName>"wininit.exe"</ProcessName>
<MemoryUsage>4080</MemoryUsage>
<PageFileUsage>1464</PageFileUsage>
</ProcessID>
- <ProcessID>
"552"
<ProcessName>"csrss.exe"</ProcessName>
<MemoryUsage>5600</MemoryUsage>
<PageFileUsage>2332</PageFileUsage>
</ProcessID>
As you can see the unique id (process id) is the same in each xml. Is there any way i can write the xml so that the information from both methods can be under one tag?
In general you can create a class which has members that have all the data you would like to collect. Then utilize some type of container ( I would suggest a dictionary keyed on process id) modify your function to take said container. If the process id is found within the container update the fields you want if it is not found add the entry. Then loop though the container and write the xml.