使用 Powershell 确定互联网连接

Determining internet connection using Powershell

是否有一个简单的 cmdlet 我可以 运行 在 PowerShell 中确定我的 Windows 机器是通过以太网还是通过无线适配器连接到互联网?我知道您可以在 GUI 上确定这一点,我只是想知道如何在 PowerShell 中管理它。

Test-Connection -ComputerName $servername

其中 $servername 是网址。使用 -Quiet 切换到 return true/false.

PowerShell cmdlet Get-NetAdapter 可以为您提供有关网络适配器的各种信息,包括连接状态。

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

另一种选择是 运行 Get-NetAdapterStatistics,它将仅向您显示来自当前连接的设备的统计信息,因此我们可以将其用作了解谁连接到网络的方式。

Get-NetAdapterStatistics

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

更好的答案

做了一些更多的研究,发现如果一个适配器有一个到 0.0.0.0 的路由,那么它就在网络上。这导致了这条管道,它将 return 仅连接到网络的设备。

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 

我写了一个函数来做这个。它应该适用于所有版本的 PowerShell,但我没有在 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)
}
Get-NetConnectionProfile

将为每个连接的网络适配器return这样的东西:

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

您应该能够使用 IPv4Connectivity 或 IPv6Connectivity 为您提供所需的 true/false 值,例如以下检查 Windows 是否认为任何 IPv4 网络设备已连接到互联网:

((Get-NetConnectionProfile).IPv4Connectivity -contains "Internet")