Search code examples
powershellprintingserverimport-csv

I need to add multiple printers to multiple print servers with Powershell and a single .csv file


I have a script that will run against an Excel file for a list of printers as well as the the listed print server.

The issue I cant figure out is how to add multiple printers to multiple print servers without having an Excel sheet with 200 lines.

I would like to have the print servers listed in the Powershell script and have the foreach command go through each server listed dynamically.

Here is the code I have so far. I am trying to get the $server to be able to have a list of servers and change the part in the function to the next server on the list. I attached an example of what the .csv formatting looks like. example of the formatting of the .csv file Thanks for any help anyone can provide.

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

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

$printers = Import-Csv C:\test\NewPrinters.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
}

Solution

  • No need to reinvent the wheel when you can use the existing commands for printer management.

    Add-PrinterPort and Add-Printer will what you want:

    foreach ($printer in $printers) {
        Add-PrinterPort -ComputerName $printer.Printserver -Name $printer.Portname -PrinterHostAddress $printer.IPAddress
        Add-Printer -ComputerName $printer.Printserver -Name $printer.Printername -DriverName $printer.Driver -Shared -ShareName $printer.Sharename -PortName $printer.Portname -Comment $printer.Comment -Location $printer.Location
    }
    

    EDIT:

    For multiple servers:

    $servers = "printserver01","printserver02","printserver03"
    
    foreach ($server in $servers) {
        foreach ($printer in $printers) {
            Add-PrinterPort -ComputerName $server -Name $printer.Portname -PrinterHostAddress $printer.IPAddress
            Add-Printer -ComputerName $server -Name $printer.Printername -DriverName $printer.Driver -Shared -ShareName $printer.Sharename -PortName $printer.Portname -Comment $printer.Comment -Location $printer.Location
        }
    }