【问题标题】:Powershell mail alert when multiple services are stopped on multiple servers当多个服务器上的多个服务停止时,Powershell 邮件警报
【发布时间】:2021-09-22 18:52:51
【问题描述】:

每当多个服务器停止多个服务时,我都会尝试接收单个邮件警报。如果有停止的服务,我制作了一个邮件函数以在循环中调用它。我制作的脚本有效,但它为每个停止的服务发送多封邮件,因为它在循环中......

知道如何在一封邮件中编译所有详细信息吗?


#Clear values in variable in case report needs to be re-run to avoid duplicate info on the html report 
Clear-Variable -Name "Body"
Clear-Variable -Name "Body1" 
Clear-Variable -Name "serviceslist"
Clear-Variable -Name "service"
Clear-Variable -Name "machines"
Clear-Variable -Name "server"

Function SendMailFromPowershell () { 

Get-Service -Name $service -ComputerName $server | Select MachineName, Name, DisplayName, Status, StartType | Sort-Object Name | ConvertTo-Html -Head $Header | Out-File -FilePath ".\report.html"


 $Body1 = "<br><h2>Please ensure all services are stopped before cleanup</h2><br>"
 $Body1 += Get-Content (".\report.html")
 
$Body = Out-String -InputObject $Body1 #( This basically converts the Sysytem.Object to System.String) 

$SMTPServer = "prodsmtp.ncc.local" 
$EmailFrom = "Daily_Report@ncc.local"  
$EmailTo = @('noc ncc <noc@ncc.com>')


$EmailSubject = "IISServices on $(Get-Date -Format "yyyy-MM-dd")" 

Send-MailMessage  -SmtpServer $SMTPServer -From $EmailFrom -To $EmailTo -Subject $EmailSubject  -Body $body -BodyAsHtml

} 


$machines = 'NPRODWEB01','NPRODWEB02'
$serviceslist = 'IISADMIN','w3logsvc','WinRM','W3SVC','WAS','NetPipeActivator','NetTcpActivator','vds','WcsPlugInService','THREADORDER'



$Header ="<head>
          <meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>
          <title>IIS Services</title>"
$Header += @"
<style>
TABLE {border-width: 1px; border-style: solid; border-color: black; border-collapse: collapse;}
TH {border-width: 1px; padding: 3px; border-style: solid; border-color: black; background-color: #6495ED;}
TD {border-width: 1px; padding: 3px; border-style: solid; border-color: black;}
</style></head>
"@


  foreach ($server in $machines) { 

    foreach ($service in $serviceslist) {

      
        if(Get-Service -Name $service -ComputerName $server| Where-Object {$_.Status -eq "Running"}) {

        Write-Host "$service is Running $server" -ForegroundColor Cyan | Out-String 
        
        } 

        elseif (Get-Service -Name $service -ComputerName $server | Where-Object {$_.Status -eq "Stopped"}) { 

        Write-Host "$service is stopped on $server" -ForegroundColor Green | Out-String 
        SendMailFromPowershell
        }

        else { 

        Write-Host "$service on $server error! Please manually check on server" -ForegroundColor Green | Out-String 

        }

    } 
    
}

#SendMailFromPowershell

【问题讨论】:

  • 为了清楚起见.. 如果 [1] 一个或一些服务停止(它们应该在哪里运行)或 [2} 如果某些服务仍在运行(它们应该在哪里停止)?您的代码建议选项 [1],但电子邮件中的正文是关于选项 [2](“请确保在清理之前停止所有服务”
  • 嗨,是的,还有一堆我没有添加到这个线程的代码,这就是为什么会有评论“请确保在清理之前停止所有服务”我想要的是发送一个包含一个或多个尚未停止的服务的邮件警报,而不是为每个停止的服务接收多个邮件警报(以避免太多邮件)服务在多个服务器上运行(在负载平衡器中)。
  • 我们还没有收到您的来信.. 我的回答解决了您的问题吗?如果是这样,请通过单击左侧的 图标来考虑accepting。这将帮助其他有类似问题的人更轻松地找到它,并有助于激励其他人回答您将来可能遇到的任何问题。
  • 嗨 Theo,对于延迟回复表示歉意。事实上,这正是我想要的。再次非常感谢您的帮助。这也将有助于我将来编写其他脚本:)

标签: windows powershell server scripting taskscheduler


【解决方案1】:

感谢您解释您需要发送一封电子邮件,其中包含仍在运行的服务。
保持大部分功能体完好无损,我会这样做:

# changed the function name to comply with the PowerShell Verb-Noun naming convention
function Send-MailFromPowershell { 
    $machines     = 'NPRODWEB01','NPRODWEB02'
    $serviceslist = 'IISADMIN','w3logsvc','WinRM','W3SVC','WAS','NetPipeActivator','NetTcpActivator','vds','WcsPlugInService','THREADORDER'
    # loop over the servers 
    $result = foreach ($server in $machines) { 
        # loop over the services in the list
        foreach ($service in $serviceslist) {
            try {
                # try and get this service, jump to the catch block if something goes wrong
                $svc = Get-Service -Name $service  -ComputerName $server -ErrorAction Stop
                if ($svc.Status -eq 'Running') {
                    Write-Warning "Service '$service' is still Running on $server"
                    # output an object to be collected in $result
                    $svc | Select-Object MachineName, Name, DisplayName, Status, StartType
                }
                else {
                    Write-Host "$service is stopped on $server" -ForegroundColor Green
                }
            }
            catch {
                Write-Warning "$server error! Please manually check on server`r`n$($_.Exception.Message)"
            }
        }
    }

    # only send an email if there is something to alert (not all services were stopped)
    # the @() is needed to force $result to be an array even if it has only one item
    if (@($result).Count) {
        # convert the resulting array of objects into a HTML table
        $table = ($result | Sort-Object MachineName, Name | ConvertTo-Html -Fragment) -join [environment]::NewLine

        # create a HTML template for the email using a Here-String
        $htmlTemplate = @'
<html><head>
    <meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>
    <title>IIS Services</title>"
    <style>
        TABLE {border-width: 1px; border-style: solid; border-color: black; border-collapse: collapse;}
        TH {border-width: 1px; padding: 3px; border-style: solid; border-color: black; background-color: #6495ED;}
        TD {border-width: 1px; padding: 3px; border-style: solid; border-color: black;}
    </style>
</head>
<body>
<h2>Please ensure all services are stopped before cleanup</h2>
<br />
@@TABLE@@
</body></html>
'@

        # create a Hashtable to splat the parameters to Send-MailMessage
        $mailParams = @{
            From       = 'Daily_Report@ncc.local'
            To         = 'noc ncc <noc@ncc.com>'
            Subject    = 'IISServices on {0:yyyy-MM-dd}' -f (Get-Date)
            SmtpServer = 'prodsmtp.ncc.local'
            Body       = $htmlTemplate -replace '@@TABLE@@', $table
            BodyAsHtml = $true
        }

        # send the email
        Send-MailMessage @mailParams
    }
    else {
        Write-Host "All services were stopped. No email was sent." -ForegroundColor Green
    }
}

# call the function
Send-MailFromPowershell

【讨论】:

  • 谢谢西奥,这很有道理。发送邮件后是否可以使用“exit()”命令?目标是防止脚本运行其余命令(未包含在此线程中)如果我在循环中使用它,这将阻止脚本循环遍历所有服务以检查其状态是否正确?或者我相信我可以在调用函数“Send-MailFromPowershell”后使用它
  • @TitanL0rd 你可以在函数中执行exit,作为最后一个右括号}上方的最后一个命令,或者如果你愿意,直接在调用函数之后。两个地方都会在发送邮件后停止脚本。
猜你喜欢
  • 1970-01-01
  • 2012-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
相关资源
最近更新 更多