03 / ROUTING, DNS, AND TELEMETRY · LESSON 09

Choose a route from an exported table

Apply routing context, longest-prefix matching, and an explicit tie rule to saved routes.

15 min · learn at your pace

Scope first, specificity next

Dot-source SubnetTools.ps1 for the strict IPv4 converter and membership function. The supplied route table is a normalised JSON export with real boolean Enabled values, numeric metrics, and valid IPv4 prefixes.

Keep only enabled routes in the requested VRF that contain the destination. Choose the longest prefix before considering Metric. A more specific /25 with metric 50 wins over a matching /24 with metric 1.

State the tie policy

Among equal-length matches, this exercise chooses the lowest numeric Metric, then the alphabetically first RouteId. That final rule makes the result deterministic; it is a teaching policy, not an attempt to reproduce a particular operating system's full route selection or equal-cost multipath behaviour.

Get-Content '/home/user/routes.json' -Raw | ConvertFrom-Json | Select-Object RouteId, Prefix, Metric

Return one object with RouteId, Prefix, NextHop, and Metric. If no eligible route exists, return no object. Validate the destination even when the route list is empty.

A selected default route means the export offers a candidate next hop. It does not prove the next hop is reachable, the return path exists, or traffic is permitted. No route is installed and no packet is sent in this lab.

Go deeper

Read the official reference.

Try an example.ps1
. '/home/user/SubnetTools.ps1'
Test-IPv4Subnet '198.51.100.200' '198.51.100.128/25'
YOUR TURN

Put it into practice.

Dot-source SubnetTools.ps1. Define Select-IPv4Route -Address -Vrf -Routes. Filter enabled routes in the requested VRF, then containing prefixes. Select longest prefix, lowest numeric Metric, then alphabetical RouteId. Return RouteId, Prefix, NextHop, Metric, or no output if unmatched. Validate Address even for an empty route list.

See an explained solution
One way to solve it.ps1
. '/home/user/SubnetTools.ps1'
function Select-IPv4Route {
    param([string]$Address,[string]$Vrf,[AllowEmptyCollection()][object[]]$Routes)
    $null = ConvertTo-IPv4Number $Address
    $candidates = @(foreach ($route in $Routes) {
        if ($route.VRF -eq $Vrf -and $route.Enabled -eq $true -and (Test-IPv4Subnet $Address $route.Prefix)) {
            [pscustomobject]@{ RouteId=$route.RouteId; Prefix=$route.Prefix; NextHop=$route.NextHop; Metric=[int]$route.Metric; Length=[int]$route.Prefix.Split('/')[1] }
        }
    })
    $selected = $candidates | Sort-Object @{Expression={$_.Length};Descending=$true},Metric,RouteId | Select-Object -First 1
    if ($selected) { $selected | Select-Object RouteId,Prefix,NextHop,Metric }
}

Eligibility is checked before ordering. Prefix length has priority over metric, and RouteId supplies a deterministic final tie break. The returned object describes the exported forwarding decision only.