VB.NET collection define problem

aha_tom

New member
Joined
Oct 19, 2006
Messages
2
Programming Experience
Beginner
I am converting my WMI scripts from vbscript to VB.NET.
This one is use to get current login username from a remote computer:cool: :

Dim objWMIService, objComputer As Object
Dim colComputer As Collection
Dim logUsername As String

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

colComputer = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")
For Each objComputer In colComputer
logUsername = objComputer.UserName
Next

I got error message "Specified cast is not valid." :eek: for the red line.
Seems the type of colComputer is wrong. What should be the correct data type if it's not a collection:confused: ? I have tried use "ManagementObjectCollection". But doesn't seem work. Could anyone give some idea:rolleyes: ?
Thanks.
 
Hi jmcilhinney,

Thanks for the reply. I've successfully done this by System.Management namespace. Following are the codes.

Function whoison(ByVal strComputer As String)
Dim logUser As String
Dim theManagementScope As New ManagementScope("\\" & strComputer & "\root\cimv2")
Dim theQueryString As String = "Select * from Win32_ComputerSystem"
Dim theObjectQuery As New ObjectQuery(theQueryString)
Dim theSearcher As New ManagementObjectSearcher(theManagementScope, theObjectQuery)
Dim theResultsCollection As ManagementObjectCollection = theSearcher.Get()
For Each currentResult As ManagementObject In theResultsCollection
Try
logUser = currentResult("Username").ToString()
Catch
logUser = ""
End Try
Next
If logUser <> "" Then
strOutput = logUser & " is on " & strComputer
Else
strOutput = "No user logon " & strComputer
End If
Return strOutput
End Function

Just one more question:
Are there any potential problems access WMI objects just using GetObject function?
I have couple functions using WMI in the vbscript way. However, they works perfectly. Like this one for delete user roaming profiles:

Function clearC(ByVal strComputer As String)
Dim objWMIService As Object
Dim objFolders As Directory
Dim intProcessID As Integer
strOutput = ""
Try
objWMIService = GetObject("winmgmts:\\.\root\cimv2:Win32_Process")
objWMIService.Create("delprof /Q /I /R /C:\\" & strComputer,
Nothing, Nothing, intProcessID)
Catch ex As Exception
strOutput += ex.Message
End Try
Return strOutput
End Function

 
Back
Top