Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

Get the MAC address of the connected Wi-Fi AP with PowerShell

Background

I want to get where I am using my PC with PowerShell, without GPS information like Windows Geolocation Service.

I can retrieve the MAC addresses of Wi-Fi APs at the places I often go to, so I tried to get the MAC address of the connected Wi-Fi AP with PowerShell.

Solution

$Wifi = (Get-NetAdapter | Where-Object InterfaceType -eq 71)
if ($Wifi.Status -ne "Up") {
    Write-Host "Wi-Fi is not up"
}
$Ap = (Get-NetNeighbor -AddressFamily IPv4 | Where-Object { $_.ifIndex -eq $Wifi.ifIndex -and $_.State -eq "Reachable" })
$Ap.LinkLayerAddress

Note

  • ifIndex or InterfaceIndex is the ID of NICs, and is used as a foreign key of the result of Get-NetAdapter, Get-NetNeighbor, and Get-NetConnectionProfile.
  • You can also get the active Wi-Fi connection and its InterfaceIndex with Get-NetConnectionProfile, but the result doesn't contain its status (Disconnected or Up). You have to use Get-NetAdapter to get the status of the NIC.
  • The meaning of InterfaceType is defined in (NetworkInterfaceType Enum)https://learn.microsoft.com/en-us/dotnet/api/system.net.networkinformation.networkinterfacetype. 71 means Wireless80211. You can use this property to distinguish active Wi-Fi devices from the other active NICs like VMWare Virtual Ethernet Adapter.
  • Get-NetNeighbor returns the result for IPv4 address and IPv6 address. To get a single MAC address for Wi-Fi AP, you must unique them or specify -AddressFamily.