Home > Back-end >  Get-Printer cmdlet applied to multiple remote servers
Get-Printer cmdlet applied to multiple remote servers

Time:12-03

I'm trying to run the cmdlet "Get-Printer" and apply it to multiple computers but I get an error message I tried using double quotations marks and get a same error message.

"Get-Printer : Cannot process argument transformation on parameter 'ComputerName'. Cannot convert value to type System.String."

Get-Printer -ComputerName 'server01', 'server02'|select-object -Property Name, PortName |Select-String -Pattern 127.0.0.1

is it because get-printer cmdlet can only be applied to one server at a time? do I have to take a different approach to be able to apply it to multiple servers?

CodePudding user response:

ComputerName is a string not an array. See the documentation for Get-Printer.

You can however use another pipe (|) at the beginning followed by a block beginning with a % (shorthand for ForEach-Object) in order to feed the strings to the cmdlet one at a time. It would look something like this:

'server01', 'server02' | 
    %{Get-Printer -ComputerName $_} | 
    Select-Object -Property Name, PortName |
    Select-String -Pattern 127.0.0.1

There is a second issue with this though. Select-String also expects a string, but you're passing it an object containing Name and PortName. Instead of using Select-String, you could probably just pipe it to a block prefixed by ? (shorthand for Where-Object) and check if PortName contains 127.0.0.1.

Adding this would look like:

'server01', 'server02' | 
    %{Get-Printer -ComputerName $_} | 
    Select-Object -Property Name, PortName |
    ?{$_.PortName.Contains("127.0.0.1")}

If you would like, you can also shorten Select-Object to just Select, but I'll leave that up to you.

CodePudding user response:

The help of Get-Printer shows that the parameter -ComputerName accepts input of type string, but not string array. So you can only specify a single computer name. https://docs.microsoft.com/en-us/powershell/module/printmanagement/get-printer?view=windowsserver2019-ps

What you can do however, is to define the array of computer names first and then use a foreach.

 $computers = "server01","server02"
 foreach($computer in $computers)
 {
    Get-Printer -ComputerName $computer |select-object -Property Name, PortName | Select-String -Pattern 127.0.0.1
 } 

Or like Jessi suggested above a one liner would look like this:

 "server01","server02" | ForEach-Object {Get-Printer -ComputerName $_} | Select-Object -Property Name, PortName | Select-String -Pattern 127.0.0.1 
  • Related