Monday 24 September 2012

Threat Management Gateway Monitoring with PowerShell


I knocked up this quick and dirty script to help find the cause of a memory issue for a client but it could easily be extended to automate and monitor any number of TMG tasks.

As is, the script lists non-paged memory pool usage and the number of active firewall sessions, but the main purpose in posting it here is to demonstrate how to access Microsoft Threat Management Gateway COM objects through PowerShell.


$smtpserver = "EXCHANGE001"
$sender = "monitoring@clientdomain.example"
$client = "Client Name"
$recipient = "support@mydomain.example"
$subject = "TMG Monitoring"


$FPC = New-Object -ComObject FPC.root
$TMGArray = $FPC.GetContainingArray()
$SessionMonitor = $TMGArray.SessionsMonitors.SessionsMonitorFirewall
$TMGFilter = New-Object -ComObject FPC.FPCFilterExpressions
$SessionMonitor.ExecuteQuery($TMGFilter,10000)
$count = 0
$SessionMonitor | forEach-Object {$count++}


$message = $message + "<p>TMG Firewall Session Count: " + $count + "</p>"
$message = $message + "<p>TMG Non-Paged Pool Memory Usage (bytes)</p>"
$message = $message + "<table>"
$message = $message + "<tr><th>Process</th><th>PID</th><th>Non-Paged Memory (bytes)</th></tr>"
$procs = get-process | ? {$_.NPM -gt 1000000} | select Name, Id, NPM | sort "NPM" -Descending
Foreach ($proc in $procs) {
         $message = $message + "<tr><td>" + $proc.Name + "</td><td>" + $proc.Id + "</td><td>" + [math]::round($proc.NPM/1024) + "</td></tr>"
}
$message = $message + "</table>"

write $message

$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$msg = new-object Net.Mail.MailMessage
$msg.From = $sender
$msg.To.Add($recipient)
$msg.Subject = $subject
$msg.Body = $message
$msg.IsBodyHTML = $true
$smtp.Send($msg)