function tcp-scan{
    param(
        [switch]$range,
        [string]$ip,
        [ValidateRange(1,65535)]
        [int]$port,
        [int]$begin,
        [int]$end
    )
    $check_connection = {
        param ([string]$ip, [int]$port);
        $tcp_client = new-Object system.Net.Sockets.TcpClient         
        $conn = $tcp_client.BeginConnect($ip, $port, $null, $null) 
        $ok = $conn.AsyncWaitHandle.WaitOne(1000,$false) 
        if ($ok) {
            $error.clear()
            $tcp_client.EndConnect($conn) | out-Null 
            if (-not $Error[0]) {
                echo "Port:$port is open"
            }
        }
    }

    $res = Test-Connection $ip  -Count 1 -ErrorAction SilentlyContinue
    if (-not $res) { 
        return "That IP is not alive"
        } else{
            printMessage -message "Scanning..."
         }
    if($range)
    { 
        $pool = [RunspaceFactory]::CreateRunspacePool(1, 100)
        $pool.open()
        $runspaces = @()
        if($begin -le $end)
        {
            for($p=$begin; $p -le $end; $p++){
                $runspace = [powershell]::create()

                $null = $runspace.addscript($check_connection)
                $null = $runspace.addargument($ip)
                $null = $runspace.addargument($p)

                # Create new runspace
                $runspace.runspacepool = $pool
                $runspaces += @{pipe=$runspace; Status=$runspace.begininvoke()}
            }

            # Wait all runspaces
            while ($runspaces.status -ne $null)
            {
                $finished = $runspaces | where { $_.status.iscompleted -eq $true };
                
                # Clear completed tasks
                foreach ($runspace in $finished)
                {
                    $runspace.pipe.endinvoke($runspace.status)
                    $runspace.status = $null            
                }
            }

            $pool.close();
            $pool.dispose();
        }
    }
    elseif($port)
    { 

         try
        {
            (New-Object System.Net.Sockets.TcpClient).Connect($ip, $port)
        }
        catch
        {
           
        }
        if(echo $?)
        {
            echo "Port:$port is open"               
        } 
    }
}