Powershell [System.Printing] – Add/Remove network printers – WMI alternative

Script

###########################################################################
#
# NAME: EP-Printer-Connction.ps1
#
# AUTHOR:  smulpuru
#
# COMMENT: Adding network printers using .Net System.Printing Class
#
# VERSION HISTORY:
# 1.0 3/2/2012 - Initial release
#
###########################################################################
Add-Type -AssemblyName System.Printing 
$printerTXT = "\\FILESRV01\Printer_Scripts\EPprinters.txt"
if(Test-Path $printerTXT)
{
    $allRead = Get-Content $printerTXT
    #for citrix using sessionstate monitor - http://support.citrix.com/article/CTX127491 - 
    #$endPointClientName will hold ClientName environment varible
    #for regular windows environment $endPointClientName will be the hostname
    #since i am using this for Citrix XenDesktop
    $endPointClientName = $(cat env:\ClientName)
    #Checking if the EP is listed in TXT file
    if($allRead -match $endPointClientName)
    {
    #Local Machine 
    $LPS = New-Object System.Printing.LocalPrintServer 
    #Network Printers Only
    $printQueuesOnLocalServer = $LPS.GetPrintQueues(`
            @([System.Printing.EnumeratedPrintQueueTypes]::Connections))
    foreach ($LPQ in $printQueuesOnLocalServer)
        {
            #Delete All Network Printers
            if($LPS.DisconnectFromPrintQueue($LPQ))
            {
            #Log Success
            }
        }
    #Go through each line of the txt file and find the line where the EP assigned printer.     
    #e.g line > clientmachine007, \\PrintServer2\HP002, \\PrintServer4\XER004
    $allRead | Select-String $endPointClientName* | foreach { `
            $_.ToString().Split(",") | foreach { `
            
                if($_ -ne $endPointClientName)
                {
                if($LPS.ConnectToPrintQueue($_))
                {
                #Log Success
                }                
                }
            }
        }
    }
}

Download

EP-Printer-Connction.ps1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s