Reputation: 568
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
Reputation: 2368
The following code:
Out-GridView
to allow user to select the desired printer(s).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
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