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
orInterfaceIndex
is the ID of NICs, and is used as a foreign key of the result ofGet-NetAdapter
,Get-NetNeighbor
, andGet-NetConnectionProfile
.- You can also get the active Wi-Fi connection and its
InterfaceIndex
withGet-NetConnectionProfile
, but the result doesn't contain its status (Disconnected
orUp
). You have to useGet-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
meansWireless80211
. 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 mustunique
them or specify-AddressFamily
.