How to get the default gateway from powershell?

后端 未结 5 2220

If a computer has multiple gateways, how can I determine which is the default gateway using the PowerShell?

5条回答
  •  春和景丽
    2020-12-18 05:56

    You need to know which of the multiple gateways are used? If so. From what I remember, when multiple gateways are available the gateway with the lowest metric("cost" based on link speed) is used. To get this, run the following command:

    Get-WmiObject -Class Win32_IP4RouteTable |
      where { $_.destination -eq '0.0.0.0' -and $_.mask -eq '0.0.0.0'} |
      Sort-Object metric1 | select nexthop, metric1, interfaceindex
    

    if there are multiple default gateways with the same cost, I think it's decided using the binding order of the network adapters. The only way I know to get this is using GUI and registry. To include binding order you could save the output of the script over, get the settingsid from Win32_networkadapterconfiguration (identify using interfaceindex), and read the registry key HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\Linkage\Bind. This key lists the binding order it seems, and the settingsid you get from win32_networkadapterconfiguration is the GUID they identify the device with. Then sort the gateways with equal metrics using their order in the Bind reg.key and you got your answer.

    Explained in: Technet Social - NIC adapter binding

提交回复
热议问题