03 / BUILD A TCP PORT SCANNER · LESSON 11

Build the port scanner

Build a sequential scanner with an injected probe, bounded scope, and one result for every endpoint.

22 min · learn at your pace

Keep transport behind one small contract

Your scanner accepts a Probe script block with three positional arguments: computer name, port, and timeout milliseconds. The adapter returns one object with Status, numeric ElapsedMs, and Detail. The scanner owns the target identity and output schema.

Dot-source the supplied ScanPlan.ps1 to reuse validated planning. Fully materialise that plan before calling the adapter. Then make exactly one probe call for each distinct pair, passing the requested timeout unchanged. Catch failures per pair so a thrown error does not hide later endpoints.

Validate adapter results. Empty output, multiple output objects, an unknown status, or a missing, negative, or non-finite duration become Error records with a diagnostic. Helpers must keep logging off the success pipeline so it cannot masquerade as a second result.

Use the simulated transport here

After defining the function, you can try it with this adapter:

$probe = { param($name,$portNumber,$limit) Test-LabTcpPort $name -Port $portNumber -TimeoutMs $limit }
# Import LabFleet.psm1, then pass $probe to Invoke-PortScan.

The scanner passes a deadline contract; an arbitrary injected script block can ignore it. The browser's overall 30-second execution limit remains the outer bound. We deliberately avoid parallelism and hidden retries.

Optional: run real TCP probes in your own lab

Download the local scanner and TCP adapter. It requires local PowerShell 7.4 or later, uses an explicit allowlist, and defaults to planning without network access. Review the script, then pass the explicit Execute switch for systems you are authorised to test. Add WhatIf to preview even with Execute selected. It uses cancellable TcpClient.ConnectAsync and disposes each client. It is optional and never runs inside this browser lab. Its comment help includes a local usage example.

Go deeper

Read the official reference.

Try an example.ps1
Import-Module '/home/user/LabFleet.psm1' -Force
. '/home/user/ScanPlan.ps1'
Get-ScanPlan @('app01','web01') @(443,5985) @('app01','web01')
YOUR TURN

Put it into practice.

Dot-source ScanPlan.ps1 and define Invoke-PortScan(ComputerName, Port, AllowedComputer, Probe, TimeoutMs=200). Validate TimeoutMs in 1–5000 and require a probe. Materialise the validated plan first, invoke Probe(name,port,timeout) once per pair, and return ComputerName, Port, Status, ElapsedMs, Detail. Convert thrown or invalid adapter results into Error rows with elapsed 0 and a diagnostic; continue. Do not execute a demonstration at load time.

See an explained solution
One way to solve it.ps1
. '/home/user/ScanPlan.ps1'
function Invoke-PortScan {
    param([string[]]$ComputerName,[int[]]$Port,[string[]]$AllowedComputer,
          [scriptblock]$Probe,[ValidateRange(1,5000)][int]$TimeoutMs=200)
    if(-not $Probe) { throw 'A probe adapter is required' }
    $plan=@(Get-ScanPlan $ComputerName $Port $AllowedComputer)
    foreach($pair in $plan) {
        try {
            $result=@(& $Probe $pair.ComputerName $pair.Port $TimeoutMs)
            if($result.Count -ne 1 -or $result[0].Status -notin @('Open','Refused','TimedOut','Error')) { throw 'Invalid probe result' }
            if($result[0].ElapsedMs -isnot [ValueType]) { throw 'Missing numeric duration' }
            $elapsed=[double]$result[0].ElapsedMs
            if([double]::IsNaN($elapsed) -or [double]::IsInfinity($elapsed) -or $elapsed -lt 0) { throw 'Invalid duration' }
            $status=$result[0].Status; $detail=[string]$result[0].Detail
        } catch { $status='Error'; $elapsed=0; $detail=$_.Exception.Message }
        [pscustomobject]@{ComputerName=$pair.ComputerName;Port=$pair.Port;Status=$status;ElapsedMs=$elapsed;Detail=$detail}
    }
}

The scanner owns planning, identity, and reporting. A replaceable adapter owns the connection attempt. Per-endpoint error conversion keeps coverage visible and enables deterministic tests.