How to get the default gateway from powershell?

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

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

回答1:

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



回答2:

If you're on PowerShell v3, you can use Get-NetIPConfiguration e.g.:

Get-NetIPConfiguration | Foreach IPv4DefaultGateway 


回答3:

I found it as the below which lists all active gateways, correct me if I am wrong

(Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway



回答4:

Use the WMI queries to pull the data that you're looking for. Below is a fairly simple example to pull the default gateway for a device specified in the first line variable. This will query the device for network adapters and display the found information (for each adapter) to the console window - pulls adapter index, adapter description, and default gateway

Shouldn't take much to expand this to process multiple devices, or process based on a list fed via an input file.

 $computer = $env:COMPUTERNAME  Get-WmiObject win32_networkAdapterConfiguration -ComputerName $computer |  Select index,description,defaultipgateway | Format-Table -AutoSize 


回答5:

I think this will be more cross platform:

 Get-NetRoute |     where {$_.DestinationPrefix -eq '0.0.0.0/0'} |     select { $_.NextHop } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!