powershellpowershell-cmdlet

Determining internet connection using Powershell


Is there a simple cmdlet I can run in PowerShell to determine if my Windows machine is connected to the internet through Ethernet or through the wireless adapter? I know you can determine this on the GUI, I just want to know how this can be managed in PowerShell.


Solution

  • The PowerShell cmdlet Get-NetAdapter can give you a variety of info about your network adapters, including the connection status.

    Get-NetAdapter | select Name,Status, LinkSpeed
    
    Name                     Status       LinkSpeed
    ----                     ------       ---------
    vEthernet (MeAndMahVMs)  Up           10 Gbps
    vEthernet (TheOpenRange) Disconnected 100 Mbps
    Ethernet                 Disconnected 0 bps
    Wi-Fi 2                  Up           217 Mbps
    

    Another option is to run Get-NetAdapterStatistics which will show you stats only from the currently connected device, so we could use that as a way of knowing who is connected to the web.

    Get-NetAdapterStatistics
    
    Name     ReceivedBytes ReceivedUnicastPackets       SentBytes SentUnicastPackets
    ----     ------------- ----------------------       --------- ------------------
    Wi-Fi 2     272866809                 323449        88614123             178277
    

    Better Answer

    Did some more research and found that if an adapter has a route to 0.0.0.0, then it's on the web. That leads to this pipeline, which will return only devices connected to the web.

    Get-NetRoute | ? DestinationPrefix -eq '0.0.0.0/0' | Get-NetIPInterface | Where ConnectionState -eq 'Connected'
    
    ifIndex InterfaceAlias    AddressFamily InterfaceMetric Dhcp      ConnectionState
    ------- --------------    ------------- --------------- -------   ---------------
        17      Wi-Fi 2               IPv4         1500     Enabled   Connected