Reputation: 1155
How to modify the below script, so it does not send the email when certain variables are empty?
Note: These variable ($volumes) -and ($ResultEvents) -and ($services) was part of the bigger script which contains Disk VOlume Info, Event Logs and Services list, if they are a match of certain filter.
$sendMailArgs['Body'] = $null
If ($volumes | Where-Object { ($_.'Free Space (%)'.ToDouble($cultureInfo) -lt $warnPercent) -and ($_.Label -ne 'Recovery') })
{
$sendMailArgs['Body'] += ($volumes | ConvertTo-Html -Head $htmlHead -PreContent "<H3>Server basic information for [$($Machine)</H3><HR><BR>") -join "`r`n"
}
if ($ResultEvents)
{
Write-Host "`t`tFound $($ResultEvents.Count) total ..." -ForegroundColor Green
$sendMailArgs['Body'] += "<H3>Total [$($ResultEvents.Count)]</H3>" + ($ResultEvents | ConvertTo-Html -Head $htmlHead) -join "`r`n"
}
if ($services)
{
$sendMailArgs['Body'] += "<BR><H3>Server Services <br /></H3>" + ($services | ConvertTo-Html -Head $htmlHead) -join "`r`n"
}
if (($volumes) -and ($ResultEvents) -and ($services))
{
# Footer Details
$sendMailArgs['Body'] += "<BR> For more Information, please open the website http://support.domain.com </U></B><BR><HR>"
$sendMailArgs['Subject'] = "$($machine) [$((Resolve-DnsName -Name $Machine -Type A).IPAddress)] Server Status result as of $(Get-Date -Format 'F')"
Send-MailMessage @sendMailArgs
}
}
The issue with the below script is that it always send out email even when there is nothing to display like in the below screenshot:
Upvotes: 0
Views: 519
Reputation: 61218
The thing is that the first If ($volumes | ...
is not just testing if $volumes
is something, but there it depends if the freespace is lower than a certain warning value.
Later, with if (($volumes) -and ($ResultEvents) -and ($services)) {...}
you do not test $volumes
the same way, so there could be nothing written in the body there.
I would suggest adding a new (boolean) variable on top
$isThereSomethingToEmail = $false
and set that to $true inside each if()
only when the if succeeds and you actually add a line to the body, just before or after $sendMailArgs['Body'] += ...
Then finally simply test for this variable
if ($isThereSomethingToEmail) {
# finish the splat and send the email
}
Upvotes: 1