Public/Wifi/Get-WifiCurrentConnection.ps1
|
Function Get-WifiCurrentConnection { <# .SYNOPSIS Retrieves the current Wi-Fi connection profile(s) for specified Wi-Fi adapters. .DESCRIPTION This function checks the active Wi-Fi connection(s) for one or more Wi-Fi adapters on the system. If no index is provided, it checks all available Wi-Fi adapters. It retrieves the connection profile for each selected adapter and returns the current Wi-Fi connection profile(s). If no active connection is found, it provides a verbose message. .PARAMETER Index Optional. Specifies the index or indices of the Wi-Fi adapters to check. If not provided, all adapters are checked. .PARAMETER TimeoutMS Optional. The timeout duration (in milliseconds) for retrieving the connection profile. Defaults to 10,000 milliseconds (10 seconds). .EXAMPLE Get-WifiCurrentConnection -Index 0 Retrieves the current Wi-Fi connection profile for the Wi-Fi adapter at index 0. .EXAMPLE Get-WifiCurrentConnection Retrieves the current Wi-Fi connection profile for all available Wi-Fi adapters. .NOTES The function uses asynchronous tasks to retrieve connection profiles with a specified timeout. #> [OutputType([Windows.Networking.Connectivity.ConnectionProfile])] Param( [Parameter(Position = 0)] [int[]]$Index, [Parameter(Position = 1)] [int]$TimeoutMS = 10000 ) Process { try { $Adapters = Get-WiFiAvailableAdapter if ($null -eq $Adapters -or $Adapters.Count -eq 0) { Write-Warning "No WiFi adapters found to check connections." return $null } # Determine which adapters to target based on Index $Targets = if ($PSBoundParameters.ContainsKey('Index')) { foreach ($i in $Index) { if ($i -ge 0 -and $i -lt $Adapters.Count) { $Adapters[$i] } else { Write-Warning "Index $i skipped: does not exist (range: 0 to $($Adapters.Count - 1))." } } } else { $Adapters # Default: Check all } $Results = [System.Collections.Generic.List[Object]]::new() foreach ($Adapter in $Targets) { $Task = $Adapter.NetworkAdapter.GetConnectedProfileAsync() $ResultType = [Windows.Networking.Connectivity.ConnectionProfile] # Await the async task $CurrentWifiProfile = Await -WinRtTask $Task -ResultType $ResultType -TimeoutMs $TimeoutMS if ($null -ne $CurrentWifiProfile) { $Results.Add($CurrentWifiProfile) } } if ($Results.Count -eq 0) { Write-Verbose "No active WiFi connection found on the selected adapter(s)." return $null } return $Results.ToArray() } catch { Write-Error "Failed to retrieve current connection: $($_.Exception.Message)" return $null } } } Register-ArgumentCompleter -CommandName 'Get-WifiCurrentConnection' -ParameterName 'Index' -ScriptBlock $ScriptBlockArgumentCompleterIndex |