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 }