简体   繁体   English

Powershell中的PC ping脚本

[英]PC ping script in Powershell

The script constantly pings a list of PC hostnames from the import CSV column 1. 该脚本会从导入CSV列1不断ping通PC主机名列表。

Column 1 (Hostname) Column 2 (User) ←Manually updated field. 第1列(主机名)第2列(用户)←手动更新的字段。

When the script recognises 3 failed ping attempts, it emails our email address with Time/Hostname/Owner (Taken from the .csv file) From/IP address/Failed Pings. 当脚本识别出3次ping操作失败时,它将通过时间/主机名/所有者(来自.csv文件)从/ IP地址/失败的Ping电子邮件发送给我们的电子邮件地址。

This works perfectly. 这很完美。 However, when the the PC comes back online it sends another email with the above but will not show the correct owner. 但是,当PC重新联机时,它会发送另一封包含上述内容的电子邮件,但不会显示正确的所有者。 Can someone please help with associating $Back "owner" with the appropriate User? 有人可以帮助将$Back “所有者”与适当的用户相关联吗? Like it works with the initial email response. 就像它可以与初始电子邮件回复一起使用。 At the moment it will either show nothing or the last name in the User column on the email, regardless the first notification email is correct. 目前,无论第一个通知电子邮件是正确的,它都不会在电子邮件的“用户”列中显示任何内容或姓氏。

$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

Either add the $Owner to the WMI object at the first embedded loop after Script Begin Message (and use ...Owner = $Result... ): 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 {
...

Or forget about the owner in the first embedded loop and retrieve the owner on the fly ( Owner = $Computers | Where {$_.Name = $Result.PSComputerName} ) in the foreach ($Result in $Results) {... loop: 或者在第一个嵌入式循环中忘记所有者,然后在foreach ($Result in $Results) {...即时获取所有者( 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"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM