一封电子邮件来统治它们

时间:2016-07-13 22:16:21

标签: email powershell scripting ping

我有这个脚本,它接受CSV并ping服务器并告诉我他们的状态,然后给我发送一封无法访问的电子邮件。下面的脚本工作得很好,但我唯一想改变的是不是每个无法访问的服务器接收多封电子邮件,而是收到一封包含所有服务器的电子邮件,这些服务器在完成ping操作后无法访问。

我知道问题的一部分是我在IF中有电子邮件行,Else。所以我在考虑创建一个变量并做一个新的行,但我需要帮助来看看它是什么样的。

任何帮助或建议将不胜感激。我已经尝试过查看微软的脚本页面并使用谷歌搜索。

$hostnamestxt = "C:\Scripts\printers.csv"
$servers = Import-Csv "$hostnamestxt"
$date = get-date

foreach($server in $servers) {
    $serverName = $server.Name
    $serverAddress = $server.IP
    if (test-Connection -ComputerName $serverAddress -Count 2 -Quiet)
    {   
        write-host "$serverName is ONLINE" -foregroundcolor black -backgroundcolor green 
    }  
    else 
    {  
        write-host "$serverName, $serverAddress is OFFLINE/UNREACHABLE" -foregroundcolor black -backgroundcolor red
        Send-MailMessage -Body "$serverName, $serverAddress is OFFLINE/UNREACHABLE at $date" -From "emailaddress" -Subject "$serverName, $serverAddress is OFFLINE/UNREACHABLE at $date" -To "emailaddress" -SmtpServer "emailaddress"
    }
}

1 个答案:

答案 0 :(得分:0)

您可以创建一个空数组,然后为脱机设备添加服务器名称,然后发送电子邮件。像这样的东西可能会做你想要的:

$servers = Import-Csv -Path "C:\Scripts\printers.csv"
$date = get-date
$Array = @()

foreach ($server in $servers) {
    $serverName = $server.Name
    $serverAddress = $server.IP

        if (test-Connection -ComputerName $serverAddress -Count 2 -Quiet)
        {   
            write-host "$serverName is ONLINE" -foregroundcolor black -backgroundcolor green 
        } 

        else 
        {  
            write-host "$serverName, $serverAddress is OFFLINE/UNREACHABLE" -foregroundcolor black -backgroundcolor red
            $Array += $serverName
        }
}

Send-MailMessage -Body "The Following Devices are Offline $Date: $Array" -From "emailaddress" -Subject "Servers Offline $date" -To "emailaddress" -SmtpServer "emailaddress"