Skip to content

Get-NetworkRouteInfo

Windows: Retrieves the IP routing table from a computer

#Requires -Version 5.1
#Requires -Modules NetTCPIP

[CmdletBinding()]
Param (
    [string]$DestinationPrefix = "*",

    [ValidateSet('IPv4', 'IPv6')]
    [string]$AddressFamily,

    [string]$ComputerName = $env:COMPUTERNAME,

    [pscredential]$Credential
)

Process {
    try {
        $session = $null
        $routeParams = @{
            'ErrorAction' = 'Stop'
        }
        if (-not [string]::IsNullOrWhiteSpace($AddressFamily)) {
            $routeParams.Add('AddressFamily', $AddressFamily)
        }

        if ($ComputerName -ne $env:COMPUTERNAME) {
            $sessionParams = @{
                'ComputerName' = $ComputerName
                'ErrorAction'  = 'Stop'
            }
            if ($null -ne $Credential) {
                $sessionParams.Add('Credential', $Credential)
            }
            $session = New-CimSession @sessionParams
            $routeParams.Add('CimSession', $session)
        }

        $routes = Get-NetRoute @routeParams | Where-Object { $_.DestinationPrefix -like $DestinationPrefix }

        $results = foreach ($r in $routes) {
            [PSCustomObject]@{
                DestinationPrefix = $r.DestinationPrefix
                NextHop           = $r.NextHop
                InterfaceAlias    = $r.InterfaceAlias
                RouteMetric       = $r.RouteMetric
                Protocol          = $r.Protocol
                ComputerName      = $ComputerName
            }
        }

        Write-Output ($results | Sort-Object DestinationPrefix)
    }
    catch {
        throw
    }
    finally {
        if ($null -ne $session) {
            Remove-CimSession $session
        }
    }
}

Specifies the destination prefix of the route (e.g., "0.0.0.0/0"). Supports wildcards.

Specifies the IP address family. Valid values: IPv4, IPv6.

Specifies the name of the target computer. Defaults to the local computer.

Specifies a PSCredential object for remote connection.

An interactive directory of PowerShell scripts.