windowspowershellprinterslogin-scriptnetwork-printers

How can I check if a printer already exists before attempting to add it?


I recently started getting into PowerShell with very basic lines/scripts. I need some assistance with a printer script that I have that runs under a user's login at logon.

Currently, every time the users log in the printer script will run (even if the printers are added, it will re-add them). This takes a while each time and I feel I could be smarter about how this is done.

I'd like to reconfigure the script to only run if the printers do not exist.

Below is my code:

add-printer -connectionname "\\PRINT01.mydomain.local\L1-Printer1"
add-printer -connectionname "\\PRINT01.mydomain.local\L1-Printer2"
add-printer -connectionname "\\PRINT01.mydomain.local\L1-Printer3"

Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" -Name "LegacyDefaultPrinterMode" -Value 1 –Force
$wsnObj = New-Object -COM WScript.Network
$wsnObj.SetDefaultPrinter("\\PRINT01.mydomain.local\L1-Printer1")

Real names have been redacted for privacy purposes!

EDIT

Get-Printer output below:

Name                           ComputerName    Type         DriverName                PortName        Shared   Published  DeviceType     
----                           ------------    ----         ----------                --------        ------   ---------  ----------     
Microsoft XPS Document Writer                  Local        Microsoft XPS Document... PORTPROMPT:     False    False      Print          
L1-Printer1                                Local        HP Laserjet 700 PCL6      PORTPROMPT:     True     False      Print

Solution

  • Continuing from my comment, here's an approach you can take:

    $printersList = @('L1-Printer1','L1-Printer2','L1-Printer3')
    $printersList | ForEach-Object -Begin {
            $printersMapped = Get-Printer
        } -Process {
            if ($_ -in $printersMapped.Name) {
                Write-Verbose -Message "$_ already mapped!"
                #continue
            }
            else {
                Write-Verbose -Message "Mapping printer $_"
                Add-Printer -ConnectionName ("\\PRINT01.mydomain.local\" + $_)
            }
        } -End {
            # if printer is default do nothing.
            # else: set default.
        }    
    

    We can create an array of the printer's that are supposed to be there. Loop through each one, while making a single call to Get-Printer to check if it's there or not. Then map the printer if it's not.

    There is some sudo-code in the -End clause that you can implement to set the printer as default if not already set.