Recently I had the need to create shared printers on a Windows Server 2008 R2 print server. The naming convention had to be strict and it was taking some time to set up the printers manually. After looking on the web I came across this site (http://poshcode.org/1462) which gave me the following code to set up the printers via PowerShell calling out the Win32_Printer WMI:

 

function CreatePrinterPort {
$server = $args[0]
$port = ([WMICLASS]“\\.\ROOT\cimv2:Win32_TCPIPPrinterPort”).createInstance()
$port.Name= $args[1]
$port.SNMPEnabled=$false
$port.Protocol=2
$port.HostAddress= $args[2]
$port.Put()
}

function CreatePrinter {
$server = $args[0]
$print = ([WMICLASS]“\\.\ROOT\cimv2:Win32_Printer”).createInstance()
$print.drivername = $args[1]
$print.PortName = $args[2]
$print.Shared = $true
$print.Published = $false
$print.Sharename = $args[3]
$print.Location = $args[4]
$print.Comment = $args[5]
$print.DeviceID = $args[6]
$print.Put()
}

$printers = Import-Csv “printers.csv”

foreach ($printer in $printers) {
CreatePrinterPort $printer.Printserver $printer.Portname $printer.IPAddress
CreatePrinter $printer.Printserver $printer.Driver $printer.Portname $printer.Sharename $printer.Location $printer.Comment $printer.Printername
}

I first populated the CSV file with the following headers:

Printserver, Driver, Portname, IPAddress, Sharename, Location, Comment, Printername

I then put in the values required for each of the printers that I wanted to set up and in many of the fields used copy and paste to save time.

I then ran the script under a PowerShell that was run as Administrator and the following is outputted when creating the printer:

image

The script will create the TCPI/IP port as needed and set up the printer according to the settings that you put in the CSV file.

One thing to note is the TCP/IP port that gets created in this script has been hardcoded to 2 which means create a LPT port. Changing this to 1 will create a RAW port.

Stay tuned for more blogs on using the Win32_Printer command.

Cheers

Paul

Post to Twitter