• Printer enumeration (why doesn't this work) VB
    2 replies, posted
I am trying to fetch a list of shared printers from the printer server where I work. This is the code so far: [CODE]Function getPrinters() Dim moReturn As System.Management.ManagementObjectCollection Dim moSearch As Management.ManagementObjectSearcher Dim mo As Management.ManagementObject Dim ms As New ManagementScope("\\fs-vgs20-01\") MsgBox("Starting") ms.Connect() moSearch.Scope = ms MsgBox("And we're off") Try moSearch = New Management.ManagementObjectSearcher("Select * from Win32_Printer") moReturn = moSearch.Get For Each mo In moReturn MsgBox(mo("name")) Next Catch ex As Exception MsgBox(ex.Message) Finally moReturn = Nothing moSearch = Nothing mo = Nothing End Try End Function[/CODE] fs-vgs20-01 is the server with the printers. It works perfectly. However when I try to run this, of course it has to be run with runas *admin account* (otherwise it does nothing at all, no error or anything), and then it returns the good old "object reference not set to an instance of an object" on the line moSearch.Scope = ms. What? If I don't set moSearch.Scope, it works, but only returns printers from the local computer (that appears to be the default scope).
You're trying to assign moSearch.Scope before you assign moSearch to anything, on the third line you are only creating a variable to hold the type of Management.ManagementObjectSearcher, you need to also assign it (before you try and use it, not after). So, either move moSearch.Scope = ms below moSearch = New Management.ManagementObjectSearcher("Select * from Win32_Printer") or vice versa.
WOW I am the worst programmer ever; programmed for 8 years and I didn't spot that. However, another problem has arisen: it doesn't actually read the printers from the printer server, but quite simply continues to read printers from the local computer as if I hadn't set the scope at all. EDIT: ms.path.ToString is \\.\root\cimv2, doesn't this indicate that it hasn't actually changed to fs-vgs20-01?
Sorry, you need to Log In to post a reply to this thread.