Public/Wifi/Get-WifiAvailableNetworks.ps1

Function Get-WifiAvailableNetworks {
  <#
.SYNOPSIS
    Retrieves available Wi-Fi networks for a specified device or all devices.
 
.DESCRIPTION
    This function retrieves a list of available Wi-Fi networks either for a specific network
    adapter (identified by its name) or for all network adapters on the system. It checks the
    Wi-Fi radio availability and handles device selection based on the provided device name.
    If no device name is specified, networks from all available Wi-Fi adapters are returned.
 
.PARAMETER DeviceName
    Optional. The name of the network adapter to query for available networks. If not specified,
    networks from all adapters will be retrieved.
 
.EXAMPLE
    Get-WifiAvailableNetworks -DeviceName "Wi-Fi"
    Retrieves available Wi-Fi networks from the adapter named "Wi-Fi".
 
.EXAMPLE
    Get-WifiAvailableNetworks
    Retrieves available Wi-Fi networks from all available adapters.
 
.NOTES
    Debugging mode can be enabled with the `Debug` flag for more detailed output.
#>

  [CmdletBinding()] # Enables Write-Debug/Verbose functionality
  [OutputType([Windows.Devices.WiFi.WiFiAvailableNetwork])]
  #[OutputType([Windows.Devices.WiFi.WiFiNetworkReport[]])]
  param(
    [String]$DeviceName
  )

  Process {
    # Check Wi-Fi radio availability (assumed to be in another script block)
    &$ScriptBlockCheckWifiRadioWarn

    # Enable Debug mode if needed
    if ($PSBoundParameters.ContainsKey('Debug')) { $DebugPreference = [System.Management.Automation.ActionPreference]::Continue }

    # Find the adapter by InterfaceDescription (name from the completer)
    if (-not [string]::IsNullOrEmpty($DeviceName)) {
      $adapter = Get-NetAdapter | Where-Object { $_.InterfaceDescription -eq $DeviceName }
      
      if (-not $adapter) {
        Write-Error "Adapter '$DeviceName' not found."
        return $null # Stop execution for this item
      } else {
        # Get the GUID (InstanceID) of the adapter
        $adapterGuid = [Guid]::Parse($adapter.InstanceID).ToString()
        Write-Debug ("GUID found for {0}: {1}" -f $DeviceName, $adapterGuid)
      }
    }

    Write-Debug "DeviceName: '$DeviceName'"
    Write-Debug "Adapter GUID: '$adapterGuid'"

    # If no device is selected, return all available networks
    if ([string]::IsNullOrEmpty($DeviceName)) {
      Write-Debug "No device selected, returning all networks"
      return (Get-WiFiAvailableAdapter).NetworkReport.AvailableNetworks
    } elseif ($adapterGuid) {
      Write-Debug "Device selected, returning specific networks"
      return (Get-WiFiAvailableAdapter | Where-Object { $_.NetworkAdapter.NetworkAdapterID -match $adapterGuid }).NetworkReport.AvailableNetworks
    } else {
      Write-Debug "Invalid Device Name, please check the input."
    }
  }
}

Register-ArgumentCompleter -CommandName 'Get-WifiAvailableNetworks' -ParameterName 'DeviceName' -ScriptBlock $ScriptBlockArgumentCompleterDeviceName