How to install a shared network printer with VB.NET and WMI

Today I show you an example of how to install a network printer with VB.NET and WMI by using the AddPrinterConnection method of the wmi Win32_Printer class. Just replace hostname with the name of the printserver/workstation and queuename with the shared printer queuename.

        Try

            Dim scope As ManagementScope = New ManagementScope("root\CIMV2")
            scope.Options.Impersonation = ImpersonationLevel.Impersonate
            scope.Connect()

            Dim path As New ManagementPath("Win32_Printer")
            Dim mgtClass As New ManagementClass(scope, path, Nothing)

            Dim inputParameters As ManagementBaseObject = mgtClass.GetMethodParameters("AddPrinterConnection")
            inputParameters("Name") = "\\hostname\queuename"

            Dim outputParameters As ManagementBaseObject = mgtClass.InvokeMethod("AddPrinterConnection", inputParameters, Nothing)
            Dim returnValue As UInteger = UInteger.Parse(outputParameters("ReturnValue"))

            If (returnValue = 0) Then
                Console.WriteLine("Success")
            ElseIf (returnValue = 5) Then
                Console.WriteLine("Access Denied")
            ElseIf (returnValue = 1801) Then
                Console.WriteLine("Invalid Printer Name")
            ElseIf (returnValue = 1930) Then
                Console.WriteLine("Incompatible Printer Driver")
            End If

        Catch ex As Exception

        End Try

Lämna ett svar

E-postadressen publiceras inte. Obligatoriska fält är märkta *

Denna webbplats använder Akismet för att minska skräppost. Lär dig hur din kommentardata bearbetas.