Utka Kanibal
Utka Kanibal

Reputation: 31

Test-connection to network printers

I'm trying to get the online or offline status of all network printers using the powershell. I have two simple codes:

$servers = "myserver1", "myserver2"
gwmi win32_printer -ComputerName $servers | Where-Object {$_.shared} | %{ $prname = $_.Name; $prtname = $_.portname; $srv = $_.systemname; $status = $_.detectederrorstate; $location = $_.location; gwmi win32_tcpipprinterport -computername $servers | where { $_.Name -eq $prtname } | select @{name="Name";expression={$prname}}, @{name="Server";expression={$srv}}, @{name="Status";expression={$status}}, @{name="Location";expression={$location}}, hostaddress }

Which makes output like:

Name        : printer_name
Server      : printer_server
Status      : detectederrortate
Location    : room_number
hostaddress : printer_fqdn

And

$pp= gwmi win32_tcpipprinterport | select hostaddress 
foreach ($p in $pp) {
$pr = $p.hostaddress
if (Test-Connection -ComputerName $pr -BufferSize 16 -Count 1 -Quiet) {Write-Host "$pr is online"}

else
{write-host "$pr is offline"}
}

With output

printer_fqdn is offline
printer_fqdn is online

How can I get output like this

Name        : printer_name
Server      : printer_server
Status      : 0
Location    : room_number
hostaddress : printer_fqdn
Ping        : Online\Offline

using test-connection cmdlet and paste the result of 2nd script into the new string with ping results?

Upvotes: 0

Views: 5757

Answers (1)

Anthony Stringer
Anthony Stringer

Reputation: 2001

$servers = "myserver1", "myserver2"

$printers = gwmi win32_printer -ComputerName $servers | Where-Object {$_.shared} | select Name, @{n='Server';e={$_.systemname}}, @{n='Status';e={$_.detectederrorstate}}, Location,
@{n='HostAddress';e={
    $prtname = $_.portname
    gwmi win32_tcpipprinterport -computername $_.systemname | where { $_.Name -eq $prtname } | select -exp hostaddress
}}

$printers | % {
    $_ | Add-Member -MemberType NoteProperty -Name Ping -Value $(
        if (Test-Connection -ComputerName $_.hostaddress -BufferSize 16 -Count 1 -Quiet) {
            'Online'
        } else {
            'Offline'
        }
    )
}

$printers | sort ping, name | ft -a

Upvotes: 1

Related Questions