user2978216
user2978216

Reputation: 568

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}

Upvotes: 1

Views: 159

Answers (2)

Darin
Darin

Reputation: 2368

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) }

Upvotes: 1

aitchdot
aitchdot

Reputation: 503

You can avoid the temporary variable using a pipeline that connects to the Add-Printer command.

Add-Printer -ConnectionName (Get-Printer -ComputerName print-server |
    Out-GridView -PassThru -Title "Select printer to connect" |
    Select-Object -ExpandProperty Name -Unique |
    ForEach-Object { "\\$($_.ComputerName)\$($_.Name)" })

You pipe the output of Get-Printer into Out-GridView, the selection into ForEach-Object to format the connection name, and finally into Add-Printer.

Upvotes: 1

Related Questions