Public/Get-specLocalDeviceGateway.ps1

Function Get-specLocalDeviceGateway {
    <#
    .SYNOPSIS
    Retrieves the default gateway of the local device.
 
    .DESCRIPTION
    The Get-specLocalDeviceGateway function queries the local device to retrieve
    information about the default gateway, including its address, metric, and associated
    interface index.
 
    .EXAMPLE
    PS C:\> Get-specLocalDeviceGateway
 
    Returns an object containing the default gateway's NextHop, Metric1, and InterfaceIndex.
 
    .NOTES
    Author: owen.heaume
    Version: 1.0 - Initial release
    #>


    [CmdletBinding()]
    Param ()

    try {
        $net = Get-CimInstance -ClassName Win32_IP4RouteTable -ea Stop |
            ? {
                $_.Destination -eq '0.0.0.0' -and $_.Mask -eq '0.0.0.0'
            } |
            sort -Property Metric1 |
            select -First 1 -Property NextHop, Metric1, InterfaceIndex

        # Check if we have a result
        if (!($net)) {
            Write-Error 'No default gateway found.' -ea stop
            return
        }

        [pscustomobject]@{
            Gateway        = $net.NextHop
            Metric1        = $net.Metric1
            InterfaceIndex = $net.InterfaceIndex
        }
    } catch {
        Write-Error "An error occurred while retrieving the local device gateway: $_" -ea stop
    }
}