We help IT Professionals succeed at work.
Get Started

Complete script to send mail when port is unavailable.

hlindstrom
hlindstrom asked
on
659 Views
Last Modified: 2012-05-11
Hi,

Could someone with more skills than me complete this script to send a -email alert when I get a false  response of the port not being available.

I have the send mail function ready but can´t get it to trigger on the false response.

Script is this:


Param([string]$srv,$port=21,$timeout=3000,[switch]$verbose)
 
# Test-Port_21.ps1
# Does a TCP connection on specified port
 
$ErrorActionPreference = "SilentlyContinue"

# Gets the date
$a = Get-Date
 
# Create TCP Client
$tcpclient = new-Object system.Net.Sockets.TcpClient
 
# Tell TCP Client to connect to machine on Port
$iar = $tcpclient.BeginConnect($srv,$port,$null,$null)
 
# Set the wait time
$wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
 
# Check to see if the connection is done
if(!$wait)
{
    # Close the connection and report timeout
    $tcpclient.Close()
    if($verbose){Write-Host "Connection Timeout"}
    Return $false
}
else
{
    # Close the connection and report the error if there is one
    $error.Clear()
    $tcpclient.EndConnect($iar) | out-Null
    if(!$?){if($verbose){write-host $error[0]};$failed = $true}
    $tcpclient.Close()
}

# Return $true if connection Establish else $False
if($failed){return $false,$a}else{return $true,$a}

---------------------------------------
The Send mail function I want to use is:

      $emailFrom = "X"
      $emailTo = "X"
      $subject = "Port 21 unavailable"
      $body = "X"
      $smtpServer = "X"
      $smtp = new-object Net.Mail.SmtpClient($smtpServer)
      $smtp.Send($emailFrom, $emailTo, $subject, $body)

Many Thanks!!

//H
Comment
Watch Question
PowerShell Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE