Powershell – Creating a network printer via Powershell

network-printerpowershellprintingwindows-server-2008

I'm trying to create network printers using a Powershell script. The script below creates the port without any issues, but will not create the queue. Can you anyone confirm if this script works on Windows Server 2008? (Note, you need to have the driver installed in order for this to work).

function CreatePrinterPort {
Param (
 [string]$IPAddress
)

$port = [wmiclass]"Win32_TcpIpPrinterPort"
$newPort = $port.CreateInstance()
$newport.Name= "IP_$IPAddress"
$newport.SNMPEnabled=$false
$newport.Protocol=1
$newport.HostAddress= $IPAddress
Write-Host "Creating Port $ipaddress" -foregroundcolor "green"
$newport.Put()
}

function CreatePrinter {
    Param (
    [string]$PrinterName,
    [string]$DriverName,
    [string]$IPAddress,
    [string]$Location,
    [string]$Comment
    )

$print = [WMICLASS]"Win32_Printer"
$newprinter = $print.createInstance()
$newprinter.Drivername = $DriverName
$newprinter.PortName = "IP_$IPAddress"
$newprinter.Shared = $true
$newprinter.Sharename = $PrinterName
$newprinter.Location = $Location
$newprinter.Comment = $Comment
$newprinter.DeviceID = $PrinterName
Write-Host "Creating Printer $printername" -foregroundcolor "green"
$newprinter.Put()

}

CreatePrinterPort -IPAddress "Localhost"

CreatePrinter  -PrinterName Print1 -DriverName "HP LaserJet 4" -PortName "Localhost"`
                -Location "Office" -Comment "Test comment"

The error I'm getting is on the CreatePrinter function:

Exception calling "Put" with "0" argument(s): "Generic failure "

Best Answer

Shouldn't your PortName be "IP_$IPAddress" instead of "Localhost"?

CreatePrinter  -PrinterName Print1 -DriverName "HP LaserJet 4" -PortName "IP_123.123.123.123" -Location "Office" -Comment "Test comment"

Furthermore, your DriverName needs to be the exact name for that driver. You don't get to choose it; it's specified by the manufacturer.