PowerShell script to view SMTP server WMI stats

I’ve been playing with PowerShell a bit lately. Here’s a script I wrote today that extracts some info about the standard Windows Server SMTP service, does a little formatting on it, and sends it out to someone via GMail. (I’m sending it via GMail, since the purpose of the script is to determine if there’s anything weird going on with the SMTP service, and if there is, then it doesn’t make sense to use it to send the status e-mail.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function sendmail
{
    param ($msgtext)
    $EmailFrom = "someone@somewhere.com"
    $EmailTo = "someone@somewhere.com" 
    $Subject = "SMTP Stats" 
    $Body = $msgtext
    $SMTPServer = "smtp.gmail.com" 
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
    $SMTPClient.EnableSsl = $true 
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("somebody@gmail.com", "password"); 
    $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}
 
$smtp1 = gwmi Win32_PerfFormattedData_NTFSDRV_SMTPNTFSStoreDriver | ? { $_.Name -eq '_Total' }
$smtp2 = gwmi Win32_PerfFormattedData_SMTPSVC_SMTPServer | ? { $_.Name -eq '_Total' }
$Date = Get-Date
$output = "-----------------------------------------------`n" 
$output += "Stats from " + $smtp1.__SERVER + " on " + $date + "`n"
$output += "----------------------------------------------`n"
$output += "Messages in queue dir: " + $smtp1.Messagesinthequeuedirectory + "`n"
$output += "Remote queue length: " + $smtp2.RemoteQueueLength + "`n"
$output += "Remote retry queue length: " + $smtp2.RemoteRetryQueueLength + "`n"
$output += "`nBadmail:`n"
$output += "`tBadPickupFile: " + $smtp2.BadmailedMessagesBadPickupFile + "`n"
$output += "`tGeneralFailure: " + $smtp2.BadmailedMessagesGeneralFailure + "`n"
$output += "`tHopCountExceeded: " + $smtp2.BadmailedMessagesHopCountExceeded + "`n"
$output += "`tNDRofDSN: " + $smtp2.BadmailedMessagesNDRofDSN + "`n"
$output += "`tNoRecipients: " + $smtp2.BadmailedMessagesNoRecipients + "`n"
$output += "`tTriggeredviaEvent: " + $smtp2.BadmailedMessagesTriggeredviaEvent + "`n"
# $output
sendmail($output)

I still don’t really know PowerShell that well, but I’m learning. I picked up most of the info I needed to write this script from StackOverflow and Hey, Scripting Guy.

Leave a Reply