测试连接到网络打印机

时间:2015-12-16 14:52:19

标签: powershell printing

我正在尝试使用powershell获取所有网络打印机的在线或离线状态。我有两个简单的代码:

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

输出如下:

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

并且

$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"}
}

带输出

printer_fqdn is offline
printer_fqdn is online

如何获得这样的输出

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

使用test-connection cmdlet并将第二个脚本的结果粘贴到带有ping结果的新字符串中?

1 个答案:

答案 0 :(得分:1)

$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