Search code examples
powershellwindows-task-scheduler

Powershell mail alert when multiple services are stopped on multiple servers


I am trying to receive a single mail alert whenever multiple services are stopped from multiple servers. I made a mail function to call it in the loop if there are stopped services. The script I made works, but it send multiple mails for each stopped service as it is in the loop....

Any idea how I can compile all details in a single mail ?


#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


Solution

  • Thanks for explaining you need to send an email with services that are still running.
    Leaving most of your function body intact, I would do it like this:

    # 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