Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 530
user1951756 Avatar asked Oct 22 '15 14:10

user1951756


People also ask

How do I check my internet connection PowerShell?

PowerShell Test-Connection Just like ping, uses Test-Connection also the ICMP protocol to test the network connectivity of a network device. In the simplest form, you can type Test-Connection <computername> or <ip-address> to do a quick connectivity test.

What is the PowerShell command to identify the network status?

Get-NetworkAdapterStatus.Ps1 Produces a listing of network adapters and status on a local or remote machine. This script produces a listing of network adapters and status on a local or remote machine.

Can you ping from PowerShell?

So, how do you ping in PowerShell? Use the 'Test-Connection' applet. It's that easy. Much like you would use 'ping' in CMD, type in 'Test-Connection' followed by '-Ping', '-TargetName', and an IP address to send a ping to that device.

How do I run a traceroute in PowerShell?

To use tracert, simply open up either Command Prompt or PowerShell and type in the command tracert followed by a hostname or destination IP address.


3 Answers

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 
like image 106
FoxDeploy Avatar answered Oct 18 '22 19:10

FoxDeploy


Get-NetConnectionProfile

will return something like this for each connected network adapter using the Network Connectivity Status Indicator (the same indicator as used in the properties of a network device):

Name             : <primary DNS suffix>
InterfaceAlias   : Ethernet
InterfaceIndex   : 9
NetworkCategory  : DomainAuthenticated
IPv4Connectivity : Internet
IPv6Connectivity : LocalNetwork

Name             : <primary DNS suffix>
InterfaceAlias   : WiFi
InterfaceIndex   : 12
NetworkCategory  : DomainAuthenticated
IPv4Connectivity : Internet
IPv6Connectivity : LocalNetwork

You should be able to use the IPv4Connectivity or IPv6Connectivity to give you a true/false value what you want. The following will check if Windows thinks any network device is connected to the Internet via either IPv4 or IPv6:

$AllNetConnectionProfiles = Get-NetConnectionProfile
$AllNetConnectionProfiles.IPv4Connectivity + $AllNetConnectionProfiles.IPv6Connectivity -contains "Internet"
like image 27
Minkus Avatar answered Oct 18 '22 20:10

Minkus


I wrote a function that does this. It should work on all versions of PowerShell, but I have not tested it on XP / Server 2003.

function Test-IPv4InternetConnectivity
{
    # Returns $true if the computer is attached to a network that has connectivity to the
    # Internet over IPv4
    #
    # Returns $false otherwise

    # Get operating system  major and minor version
    $strOSVersion = (Get-WmiObject -Query "Select Version from Win32_OperatingSystem").Version
    $arrStrOSVersion = $strOSVersion.Split(".")
    $intOSMajorVersion = [UInt16]$arrStrOSVersion[0]
    if ($arrStrOSVersion.Length -ge 2)
    {
        $intOSMinorVersion = [UInt16]$arrStrOSVersion[1]
    } `
    else
    {
        $intOSMinorVersion = [UInt16]0
    }

    # Determine if attached to IPv4 Internet
    if (($intOSMajorVersion -gt 6) -or (($intOSMajorVersion -eq 6) -and ($intOSMinorVersion -gt 1)))
    {
        # Windows 8 / Windows Server 2012 or Newer
        # First, get all Network Connection Profiles, and filter it down to only those that are domain networks
        $IPV4ConnectivityInternet = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetConnectionProfile.IPv4Connectivity]::Internet
        $internetNetworks = Get-NetConnectionProfile | Where-Object {$_.IPv4Connectivity -eq $IPV4ConnectivityInternet}
    } `
    else
    {
        # Windows Vista, Windows Server 2008, Windows 7, or Windows Server 2008 R2
        # (Untested on Windows XP / Windows Server 2003)
        # Get-NetConnectionProfile is not available; need to access the Network List Manager COM object
        # So, we use the Network List Manager COM object to get a list of all network connections
        # Then we check each to see if it's connected to the IPv4 Internet
        # The GetConnectivity() method returns an integer result that can be bitwise-enumerated
        # to determine connectivity.
        # See https://msdn.microsoft.com/en-us/library/windows/desktop/aa370795(v=vs.85).aspx

        $internetNetworks = ([Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]"{DCB00C01-570F-4A9B-8D69-199FDBA5723B}"))).GetNetworkConnections() | `
            ForEach-Object {$_.GetNetwork().GetConnectivity()} | Where-Object {($_ -band 64) -eq 64}
    }
    return ($internetNetworks -ne $null)
}
like image 2
Frank Lesniak Avatar answered Oct 18 '22 20:10

Frank Lesniak