Ever needed to know whether you are currently connected to a metered (costly) network? Here is a quick way to check:

function Test-WlanMetered
{
  [void][Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType = WindowsRuntime]
  $cost = [Windows.Networking.Connectivity.NetworkInformation]::GetInternetConnectionProfile().GetConnectionCost()
  $cost.ApproachingDataLimit -or $cost.OverDataLimit -or $cost.Roaming -or $cost.BackgroundDataUsageRestricted -or ($cost.NetworkCostType -ne "Unrestricted")
} 

It is using a UWP API that returns a wealth of information about your network status, including information about network cost.

If you are on an older Windows platform, here is alternative code that uses the good old “netsh” command line tool and extracts the required information. Note that string operations (as used extensively by below code) are error-prone and may need tweaking.

At the same time below code nicely illustrates how the general-purpose string manipulation tools in PowerShell can serve as a last life line if no proper object-oriented API call is at hand:

function Test-WlanMetered
{
  $wlan = (netsh wlan show interfaces | select-string "SSID" | select-string -NotMatch "BSSID")
  if ($wlan) {
    $ssid = (($wlan) -split ":")[1].Trim() -replace '"'
    $cost = ((netsh wlan show profiles $ssid | select-string "Cost|Kosten") -split ":")[2].Trim() -replace '"'

    return ($cost -ne "unrestricted" -and $cost -ne "Uneingeschränkt" -and $cost -ne 'Uneingeschr"nkt')
  }
  else { $false }
}


Twitter This Tip! ReTweet this Tip!

Anonymous