【问题标题】:PC ping script in PowershellPowershell 中的 PC ping 脚本
【发布时间】:2017-08-22 12:22:36
【问题描述】:

脚本不断从导入 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

【问题讨论】:

    标签: powershell email ping


    【解决方案1】:

    Script Begin Message 之后的第一个嵌入循环中将$Owner 添加到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 {
    ...
    

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

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

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 1970-01-01
      • 2020-10-17
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多