Find a network route

The Linux ip tool has a really handy feature to get the route a given IP will take. Unfortunately, I know of no native Windows equivalent.

This is built for Windows 8 or Powershell v3 as it makes use of Get-NetRoute.

function Find-Route {
    param(
        [parameter(position=0,mandatory=$true)][net.ipaddress]$IP
    );

    $rs = Get-NetRoute -AddressFamily ({if($IP.AddressFamily -eq "Internetwork"){"ipv4"} else {"ipv6"}}).invoke();

    foreach($ri in $rs) {
        if(Confirm-SameSubnet $ri.DestinationPrefix.split("/")[0] $ri.DestinationPrefix.split("/")[1] $IP) {
            $ri;
        }
    }
}

Example output

Find-Route 1.1.1.1

ifIndex DestinationPrefix                              NextHop                                  RouteMetric PolicyStore
------- -----------------                              -------                                  ----------- -----------
13      0.0.0.0/0                                      192.168.0.254                                      0 ActiveStore

Find-Route 192.168.0.1

ifIndex DestinationPrefix                              NextHop                                  RouteMetric PolicyStore
------- -----------------                              -------                                  ----------- -----------
13      192.168.0.13/24                                0.0.0.0                                          256 ActiveStore
13      0.0.0.0/0                                      192.168.0.254                                      0 ActiveStore


Find-Route 8.8.4.4

ifIndex DestinationPrefix                              NextHop                                  RouteMetric PolicyStore
------- -----------------                              -------                                  ----------- -----------
13      0.0.0.0/0                                      192.168.0.254                                      0 ActiveStore

Find-Route 2001:4860:4860::8844