Powershell中的PC ping脚本

时间:2017-08-22 12:22:36

标签: powershell email ping

该脚本不断从导入CSV列1中ping一个PC主机名列表。

  

第1列(主机名)第2列(用户)←手动更新字段。

当脚本识别3次ping尝试失败时,它会通过时间/主机名/所有者(取自.csv文件)发送电子邮件地址来自/ IP地址/失败的ping。

这完美无缺。但是,当PC重新联机时,它会发送另一封包含上述内容的电子邮件,但不会显示正确的所有者。有人可以帮助您将$Back“所有者”与相应的用户相关联吗?喜欢它与初始电子邮件响应一起使用。目前,无论第一封通知电子邮件是否正确,它都将在电子邮件的“用户”列中显示任何内容或姓氏。

$computers = Import-Csv C:\temp\Reporting\MainHosts.csv
$Sources = @($Env:COMPUTERNAME)
$To = "Username@Email.com"#,"Username@Email.com"
$From = "Username@Email.com"
$SMTPServer = "SERVER"
[datetime]$TimeStop = "16:17"
$StartTime = Get-Date -format 'dd-MM-yyyy hh:mm:ss'

Clear-Host

$Header = @"
    <style>BODY{font-family: Arial; font-size: 11pt;}
    TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;text-align: center;}
    TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;text-align: center;}
    TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;text-align: center;}
    </style>
"@

######################Load data array (Table) ######################
$Status = @{}
foreach ($Source in $Sources) {
    foreach ($computer in $computers) {
        $computername = $($computer.Hostname)
        $owner = $($computer.User)
        $Status.Add("$Source`:$computername", [PSCustomObject]@{
            Time = ""
            Hostname = $computername
            Owner = $owner
            From = $Source
            'IP Address' = $null
            'Failed Pings' = 0
        })
    }
}

###################### Script Begin Message ######################
do {
    $Results = foreach ($Source in $Sources) {
        foreach ($computer in $computers) {
            $computername = $($computer.Hostname) #Defining the Hostname column within .csv sheet
            $owner = $($computer.User)
            try {
                Write-Host "." -NoNewline
                Get-WmiObject "Win32_PingStatus" -ComputerName $Source -Filter "Address = '$computername'" -ErrorAction Stop | Select PSComputerName,Address,IPV4Address,StatusCode
            } catch {
                Write-Warning "Error with $computername`: $($Error[0])"
            }
        }
    }

    $Back = @()
    foreach ($Result in $Results) {
        $Key = "$($Result.PSComputerName):$($Result.Address)"
        $Status[$Key].'IP Address' = $Result.IPV4Address
        $Status[$Key].Time = Get-Date
        if ($Result.StatusCode -eq 0) {
            if ($Status[$Key].'Failed Pings' -ge 3) {
                $Back += [PSCustomObject]@{
                    Time = Get-Date
                    Hostname = $Result.Address
                    Owner = $owner
                    From = $Result.PSComputerName
                    IPAddress = $Result.IPV4Address
                    Status = "Connectivity Returned"
                }
            }
            $Status[$Key].'Failed Pings' = 0
        } else {
            $Status[$Key].'Failed Pings' ++
        }
    }
    # Email Alert
    if ($Back) {
        $HTML = $Back | Sort Destination,From | ConvertTo-Html -Head $Header -PreContent "<p>Ping Detection Script has detected the following workstations are now online and <b>restored connectivity!</b><br></p>" | Out-String
        Send-MailMessage -To $To -From $From -Subject "**No Action Required** - Ping Detection Script Reporting Connections Restored" -Body $HTML -BodyAsHtml -SmtpServer $SMTPServer
    }

    $Data = $Status.Values | Where { $_.'Failed Pings' -eq 3 -or ( ($_.'Failed Pings' -ne 0 -and -not ($_.'Failed Pings' % $Alert))) }
    if ($Data) {
        $HTML = $Data | Sort Destination,From | ConvertTo-Html -Head $Header -PreContent "<p>Ping Detection Script has detected <b>Offline</b> workstations! See below list<br></p>" | Out-String
        Send-MailMessage -To $To -From $From -Subject "**Urgent Action Required** - Ping Detection Script Reporting Offline Workstations" -Body $HTML -BodyAsHtml -SmtpServer $SMTPServer
        Write-Host "Alert Email Sent!`n"
        Start-Sleep -Seconds 1
    }

    Clear-Host
    $Status.Values | Sort Destination,From | Format-Table -AutoSize
    Write-Host "Ping Script Monitoring ..." -NoNewline
    Start-Sleep -Seconds 4
} until ($Time.Hour -eq $TimeStop.Hour -and $Time.Minute -eq $TimeStop.Minute)
Write-Host "`nScript shutting down, time limit reached:  $($TimeStop.Hour):$($TimeStop.Minute)"
Write-Output $Status.Values | Sort Destination,From | Format-Table -AutoSize

1 个答案:

答案 0 :(得分:0)

$Owner之后的第一个嵌入式循环中将Script Begin Message添加到WMI对象(并使用...Owner = $Result...):

...
Try {
    Write-Host "." -NoNewline
    $Result = Get-WmiObject "Win32_PingStatus" -ComputerName $Source -Filter "Address = '$computername'" -ErrorAction Stop | Select PSComputerName,Address,IPV4Address,StatusCode
    $Result = $Result | Add-Member –MemberTypeNoteProperty –Owner $Owner
   $Result
} Catch {
...

或者忘记第一个嵌入式循环中的所有者并在Owner = $Computers | Where {$_.Name = $Result.PSComputerName}循环中动态检索所有者(foreach ($Result in $Results) {...):

$Back += [PSCustomObject]@{
    Time = Get-Date
    Hostname = $Result.Address
    Owner = $Computers | Where {$_.Name = $Result.PSComputerName}
    From = $Result.PSComputerName
    IPAddress = $Result.IPV4Address
    Status = "Connectivity Returned"
}