powershellnetwork-printersout-gridview

Select and connect network printer


How do I select printer from printserver and connect it? What is the right way to do that?

This code works but how to write better code without creating temporary variable $x ?

$x = Get-Printer -ComputerName print-server | Out-GridView -PassThru -Title "Select printer to connect" | Select @{n="ConnectionName";e={"\\$($_.ComputerName)\$($_.Name)"}} | Select -ExpandProperty ConnectionName
Add-printer -ConnectionName $x

PS: Now I did it like this. If somebody can do better feel free to propose an answer.

 Get-Printer -ComputerName print-server |
 Sort-Object |
 Out-GridView -PassThru -Title "Select printer to connect" |
 Select  @{n="ConnectionName";e={"\\$($_.ComputerName)\$($_.Name)"}} |
 ForEach-Object {Add-Printer -ConnectionName $_.ConnectionName}

Solution

  • The following code:

    1. Gets all printers on the print server.
      • This example uses a full domain path, but that is optional.
    2. Uses regex to remove all printers names that do NOT start with "pl".
      • This useful in my situation, but remove this line if not desired.
      • Use any other regex as desired.
    3. Sorts all the printers.
    4. Uses Out-GridView to allow user to select the desired printer(s).
    5. For each selected printer, format the connection name as '\\PrintServer\Printer'.
    Get-Printer -ComputerName 'print-server.domain.com' |
    Where-Object {$_.Name -match '(?i)PL.*'} |
    Sort-Object |
    Out-GridView -PassThru -Title 'Select printer to connect' |
    Foreach-Object { Add-Printer -ConnectionName ('\\{0}\{1}' -f $_.ComputerName, $_.Name) }