How to: Check if port is open with Powershell

For sys admins it is important to know if ports of certain applications are open for monitoring. One simple solution is to have a monitoring software, but if you want a cheap and cheerful solution, you can use Powershell. This can be done by the below script.

The below script will check the server/port and if the port is open, it will just print on screen saying “PORT IS OPEN – OK” and if the port is not open or the service is down, it will send and email.

Feel free to change or add to this script. You can easily put this in a loop to check all the services in your enterprise.

#PARTS THAT CAN BE CHANGED
$MailServer = "mail.mydomain.com"
$MailTo = "sysadmin@mydomain.com"
$MailFrom = "IT <noreply@mydomain.com>"
$MailBody = "Please note that the server is not reachable in this test that runs every 10 minutes. Please check the status of the server."
$MailSubject = "** PORT IS NOT REACHABLE FOR SERVER 1 **"
$Server = "SQLSRV01"
$Server_port = "1433"
#PARTS THAT CAN BE CHANGED

$socket = New-Object Net.Sockets.TcpClient
$ErrorActionPreference = 'SilentlyContinue'

#Server and port
$socket.Connect($Server,$Server_Port)
$ErrorActionPreference = 'Continue'

if ($socket.Connected) {
Write-Host "POST IS OPEN - OK"
$socket.Close()
}
else
{
send-mailmessage -To $MailTo -from $MailFrom -Subject $MailSubject -body $MailBody -smtpserver $MailServer -BodyAsHtml -Encoding ([System.Text.Encoding]::UTF8)
}

$socket = $null

Leave a Reply

Your email address will not be published. Required fields are marked *