The script below serves the purpose of searching many machines in our environment to check to see whether or not the SQL Server service is running. What it does is search through AD to get the list of computers and then gets the service status. If it is not able to connect to it by name for whatever reason, there is an else statement that records the failed server to output into a separate variable. Then, it sends a formatted email with the results in HTML tables. This is all fine except for one thing. If there are 2 or more failed connections, it only displays the last of the two failed results. This is obvious to me why this happens because the $result2 portion has no way of adding each failed result to itself as an array. So that's my question. Is there a way to accomplish this and create the array that contains all failed attempts rather than just one? I apologize for the poor formatting and I have obviously modified some of the email info for privacy. I appreciate any feedback and/or criticism. Thanks!
Import-module activedirectory$CashControls = get-adcomputer -filter 'Name -like "*-CC*" -and Name -notlike "*win7thin*" -and name -notlike "*acme*"' | sort-object | select name
$result = foreach ($computer in $CashControls){$computer.name | % {if ($s=get-service -computer $_ -name MSSQLSERVER,'MSSQL$SQLEXPRESS' -ErrorAction SilentlyContinue) {$s | select @{Name = "Machine Name"; Expression = {$Computer.Name}}, @{Name="Status"; Expression = {$_.status}}} else {$result2 = "$_"}}}
$MyObject = @()
Foreach ($Line in $result2) {
$MyCustomObject = New-Object -TypeName PSObject
Add-Member -InputObject $MyCustomObject -MemberType NoteProperty -Name "Needs Attention" -Value $Line
$MyObject += $MyCustomObject
}
$smtpServer = "smptserver@server.com"
$smtpFrom = "CCSQLMonitor@email.com"
$smtpTo = "emailaddress@email.com"
$messageSubject = "Cash Control SQL Server Service Report"
$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$message.Subject = $messageSubject
$message.IsBodyHTML = $true
$style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
$style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
$style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
$style = $style + "TD{border: 1px solid black; padding: 5px; }"
$style = $style + "</style>"
$message.Body = ($result | ConvertTo-Html -Head $Style) + "<br>" + ($MyObject | ConvertTo-Html -Property 'Needs Attention' -Head $style)
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($message)