The PowerShell cmdlet Get-NetRoute returns more results than the standard "route print" command

We've been working to migrate our server documentation tool from a combination of WMI, and low level APIs to PowerShell and have come across an interesting issue.

Microsoft recommend using the PowerShell cmdlet Get-NetRoute as a replacement for the old "route print" command, but it returns more results than the standard "route print" command and the WMI class Win32_IP4RouteTable.

It turns out that the former returns routes for interfaces that are down whereas the later two methods do not. This is what leads to the inconsistency.

To ignore the results from network adapters that aren't up you need to correlate them with the results from the Get-NetAdapter cmdlet and check the ifOperStatus.



$routes = Get-NetRoute
$adapters = Get-NetAdapter
foreach ($route in $routes)
{
    $interfaceOnline = $true
    foreach ($adapter in $adapters)
    {
        if ($adapter.InterfaceIndex -eq $route.InterfaceIndex)
        {
            if ([System.Convert]::ToInt32($adapter.ifOperStatus) -ne 1) { $interfaceOnline = $false; }
        }
    }
    if (!$interfaceOnline) { continue; }
    $route
}

Comments

Popular posts from this blog

Windows Server 2016, 2019, 2022, Windows 10 and Windows 11: Date and time "Some settings are managed by your organization".

TFTPD32 or TFTPD64 reports Bind error 10013 An attempt was made to access a socket in a way forbidden by its access permissions.

Enable function lock for F1-F12 on HP ZBook mobile workstations