Powershell: simple script for port monitoring (SMTP, HTTP, FTP, etc) using “system.net.sockets.tcpclient” class

Recently we had a requirement to check SMTP of two diffrent servers and run a script if both servers failed. i googled around for the tool but ended up putting together this script.

Its not the most prettiest but it works, and im sure you guys will make something much better out of it.

# Define the host names here for the servers that needs to be monitored
$servers = "relay1.host.com","relay2.host.com"
# Define port number
$tcp_port = "25"

# Loop through each host to get an individual result.
ForEach($srv in $servers) {

$tcpClient = New-Object System.Net.Sockets.TCPClient
$tcpClient.Connect($srv,$tcp_port)

$connectState = $tcpClient.Connected

If($connectState -eq $true) {
Write-Host "$srv is online"
}
Else {
Write-Host "$srv is offline"
}

$tcpClient.Dispose()

}

If something is wrong or if you think there is a better way please free feel to comment and let everyone know. its all about community after all.

Update 4/18/2016 –

Updated the script with the one provided by Donald Gray – Thanks a lot : )