使用我從這篇文章微調過的 PowerShell 函式
function Get-InternetConnection {
$prf = Get-NetConnectionProfile -IPv4Connectivity Internet
$nic = Get-NetAdapter -InterfaceIndex $prf.InterfaceIndex -ErrorAction Ignore
$ipi = Get-NetIPInterface -InterfaceIndex $prf.InterfaceIndex -ErrorAction Ignore
$ip = $prf | Get-NetIPAddress -AddressFamily IPv4
$dg = $prf | Get-NetIPConfiguration
$stat = if ($nic) { if ($nic.InterfaceOperationalStatus -eq 1) { 'Up' } else { 'Down' } }
$maca = if ($nic) { $nic.MacAddress }
$props = [ordered]@{
ConnectionProfile = $prf.Name
IPv4Connectivity = $prf.IPv4Connectivity
IPv6Connectivity = $prf.IPv6Connectivity
InterfaceIndex = $prf.InterfaceIndex
InterfaceAlias = $prf.InterfaceAlias
NetAdapter_InterfaceStatus = $stat
NetAdapter_InterfaceMacAddr = $maca
NetIPInterface_ConnectionState = $ipi.ConnectionState
NetIPInterface_AddressFamily = $ipi.AddressFamily
IPAddress = $ip.IPAddress
SubnetMask = $ip.PrefixLength
DefaultGateway = $dg.IPv4DefaultGateway | Select-Object -ExpandProperty NextHop
DNSServer = ($dg.DNSServer).serverAddresses
}
New-Object -TypeName PSobject -Property $props
}
這個 PowerShell Function 的使用方式如下,非常簡單:
Get-InternetConnection
這個命令主要會取得目前上網的主要網路設定檔(Network Profile),然後取得該網路設定檔的網卡與網路設定,並且完整的呈現出來。