PowerShell Dictonary过滤掉失败的ping

时间:2016-06-21 14:15:23

标签: powershell dictionary output

我正在尝试过滤状态=离线打印机并将该输出发送到电子邮件中的$ Body,有关如何执行此操作的任何想法?到目前为止,输出显示所有打印机和IT,无论在线或离线状态如何。

    Clear-Host
$printerip = @( 
"192.168.141.104","192.168.141.250","192.168.141.251","192.168.141.53","192.168.141.157","192.168.141.167",
"192.168.141.115","192.168.141.116","192.168.142.25","192.168.142.23","192.168.1 44.80","192.168.144.57","192.168.150.51",
"192.168.150.50","192.168.150.40"
)

$printername = @(
"Shoreline Color", 
"Dockside B/W", 
"Shoreline B/W",
"Spinnaker",
"BA Ricoh Printer",
"BA Xerox Color",
"BA Lab 1",
"BA Lab 2",
"Dowagiac Ricoh",
"Dowagiac Xerox Color",
"Paw Paw Ricoh",
"Paw Paw Xerox Color",
"330 Finance 1",
"330 Finance 2",
"330 Copierr"
)

$status = @()
foreach($printer in $printerip){
if(Test-Connection $printer -Count 2 -Quiet){
$status += "Online"
}else{
$status += "Offline"
}}

$count   = $printerip.Count
$counter = 0
$report  = @()
do{
$report +=$status[$counter]+" - "+$printerip[$counter]+" -     "+$printername[$counter] 
$counter++
}until($counter -ge $count)

if($report -match 'offline'){$body = ("We should probably do something about     this! `n `n") + $report | Out-String
Send-MailMessage -From "PrinterTest@domain.org" -To  "name@domain.org" -Subject "Printer Test" -Body $body  -SmtpServer   "mail.domain.org"}

1 个答案:

答案 0 :(得分:1)

在你的do...until循环中,你需要一个if语句来检查$status[$counter]是否等于'离线'才能获取离线打印机,但是,我会尝试这样的东西或尝试放置打印机信息到自己单独的csv文件

$printers = @'
IP,Name,Status
192.168.141.104,Shoreline Color,
192.168.141.250,Dockside B/W,
192.168.141.251,Shoreline B/W,
192.168.141.53,Spinnaker,
192.168.141.157,BA Ricoh Printer,
192.168.141.167,BA Xerox Color,
192.168.141.115,BA Lab 1,
192.168.141.116,BA Lab 2,
192.168.142.25,Dowagiac Ricoh,
192.168.142.23,Dowagiac Xerox Color,
192.168.144.80,Paw Paw Ricoh,
192.168.144.57,Paw Paw Xerox Color,
192.168.150.51,330 Finance 1,
192.168.150.50,330 Finance 2,
192.168.150.40,330 Copierr,
'@ | ConvertFrom-Csv

$printers | ForEach-Object {
    if (Test-Connection $_.ip -Count 2 -Quiet) {
        $_.status = 'Online'
    } else {
        $_.status = 'Offline'
    }
}

if ($printers.status -contains 'Offline') {
    $offlineprinters = $printers | Where-Object status -eq 'Offline' | Format-Table -AutoSize
    $body = "We should probably do something about this!`n`n" + $offlineprinters | Out-String
    Send-MailMessage -From 'email@domain.com' -To 'email@domain.com' -Subject 'Printer Test' -Body $body -SmtpServer 'smtp.domain.com'
}