How to get the default gateway from powershell?

后端 未结 5 2221

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

相关标签:
5条回答
  • 2020-12-18 05:38

    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
    
    0 讨论(0)
  • 2020-12-18 05:47

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

    (Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway
    
    0 讨论(0)
  • 2020-12-18 05:48

    I think this will be more cross platform:

     Get-NetRoute |
        where {$_.DestinationPrefix -eq '0.0.0.0/0'} |
        select { $_.NextHop }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-18 05:59

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

    Get-NetIPConfiguration | Foreach IPv4DefaultGateway
    
    0 讨论(0)
提交回复
热议问题