Public/Network/Get-NetworkAdapter.ps1

<#
Copyright © 2024 Integris. For internal company use only. All rights reserved.
#>


FUNCTION Get-NetworkAdapter {
    <#
    .SYNOPSIS
    Retrieves and displays information about network adapters on the system.
 
    .DESCRIPTION
    This function collects detailed information about specified network adapters, including their type, status, IP address, DNS settings, and connection profile. It supports filtering by adapter type and connection status.
 
    .PARAMETER AdapterType
    Specifies the types of network adapters to include. Valid values are "Wired", "Wireless", "VPN", "Hyper-V", "Bluetooth", and "All".
 
    .PARAMETER PhysicalOnly
    If specified, includes only physical network adapters.
 
    .PARAMETER Status
    Specifies the connection status of the network adapters to include. Valid values are "Connected" and "Disconnected".
 
    .EXAMPLE
    Get-NetworkAdapter -AdapterType "Wired", "Wireless" -Status "Connected"
 
    This command retrieves information about all connected wired and wireless network adapters.
 
    .EXAMPLE
    Get-NetworkAdapter -AdapterType "All" -PhysicalOnly -Status "Disconnected"
 
    This command retrieves information about all disconnected physical network adapters.
 
    .NOTES
    This function uses CIM instances to gather network adapter information and may require appropriate permissions to execute.
    #>


    [CmdletBinding()]
    PARAM (
        [ValidateSet("Wired","Wireless","VPN","Hyper-V","Bluetooth","All")]
        [String[]]$AdapterType = @("All"),    
        [Switch]$PhysicalOnly = $False,
        [ValidateSet("Connected","Disconnected")]
        [String[]]$Status = @("Connected","Disconnected")
    )

    $StatusCheck = $Status.Replace("Connected","Up")
   
    ### Initialize Variables
    $Adapters = @()
    $Results = @()
    $NotApplicable  = ""
    $None = ""
    $Count = 0

    ### Collect Adapter Types to Scan
    IF($AdapterType -contains "Wired" -or $AdapterType -contains "All") {
        IF ($PhysicalOnly -eq $True) { $Adapters += Get-NetAdapter -Physical | Where-Object { $_.PhysicalMediaType -eq "802.3" -and ((Test-IsPrivateIP ((Get-NetIPAddress -InterfaceIndex $_.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue).IPAddress)) -or $_.Status -eq "Disconnected") }}
        ELSE {
            TRY {
                $Adapters += Get-NetAdapter | Where-Object { $_.PhysicalMediaType -eq "802.3" -and $StatusCheck -contains $_.Status -and ((Test-IsPrivateIP ((Get-NetIPAddress -InterfaceIndex $_.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue).IPAddress)) -or $_.Status -eq "Disconnected") }
            }
            CATCH {}
        }
    }
    IF($AdapterType -contains "Wireless" -or $AdapterType -contains "All") {
        IF ($PhysicalOnly -eq $True) { $Adapters += Get-NetAdapter -Physical | Where-Object { $_.PhysicalMediaType -like "*802.11*" -and $StatusCheck -contains $_.Status }}
        ELSE { $Adapters += Get-NetAdapter | Where-Object { $_.PhysicalMediaType -like "*802.11*" -and $StatusCheck -contains $_.Status }}
    }
    IF($AdapterType -contains "Bluetooth" -or $AdapterType -contains "All") {
        IF ($PhysicalOnly -eq $True) { $Adapters += Get-NetAdapter -Physical | Where-Object { $_.PhysicalMediaType -eq "BlueTooth" -and $StatusCheck -contains $_.Status }}
        ELSE { $Adapters += Get-NetAdapter | Where-Object { $_.PhysicalMediaType -eq "BlueTooth" -and $StatusCheck -contains $_.Status }}
    }
    IF($AdapterType -contains "Hyper-V" -or $AdapterType -contains "All" -or $Adapter.Count -eq 0 -or (Test-IsServer)) {
        IF ($PhysicalOnly -eq $True) { $Adapters += Get-NetAdapter -Physical | Where-Object { $_.PhysicalMediaType -eq "Unspecified" -and $StatusCheck -contains $_.Status }}
        ELSE { $Adapters += Get-NetAdapter | Where-Object { $_.PhysicalMediaType -eq "Unspecified" -and $_.MacAddress -ne "" -and $StatusCheck -contains $_.Status }}
    }
    
    ### Collect Adapter Data
    FOREACH ($AdapterBinding in $Adapters) {
        ### Initialize Variables
        $NetAdapter = $AdapterBinding
        $ConnectedSSID = ""
        $Type = ""
        $ConnectionStatus = ""
        $SignalStrength = ""
        $Protocol = ""
        $DNSSuffix = ""
        $LinkSpeed = ""
        $vAdapterName = ""
        $VMSwitch = ""
        $DNSAssignment = ""    
        $NetConnectionProfile = ""
        $DNSServers = ""

        ### Skip if AdminStatus Down
        IF ($NetAdapter.AdminStatus -eq "Down") { continue }

        ### Progress Bar Stuff
        $Count++
        $PercentComplete = (($Count-1) / $Adapters.Count) * 100
        Write-Progress -ID 7 -Activity "Collecting Adapter Data" -Status "$([int]$PercentComplete)% - Collecting Data" -PercentComplete $PercentComplete

        ### Get Connection Status Info
        $ConnectionStatus = $NetAdapter.MediaConnectionState

        ### Get-IPAddress
        $IPAddress = (Get-NetIPAddress -InterfaceIndex $NetAdapter.ifIndex -ErrorAction SilentlyContinue | Where-Object { $_.AddressFamily -eq "IPv4" }).IPAddress

        ### Get DHCP Status
        $DHCPStatus = (Get-NetIPInterface -InterfaceIndex $NetAdapter.ifIndex -ErrorAction SilentlyContinue | Where-Object { $_.AddressFamily -eq "IPv4"}).DHCP
        IF ($DHCPStatus -eq "Enabled") { $IPAsssignment = "DHCP" } ELSE { $IPAsssignment = "Static" }

        ### DNS Assignment
        $KeyName = "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\" + $NetAdapter.DeviceName.Replace("\Device\","")
        $Value = Get-ItemPropertyValue -Path $KeyName -Name NameServer -ErrorAction SilentlyContinue
        IF ($Value -eq "" -or $null -eq $Value) { $DNSAssignment = "DHCP" }
        ELSEIF ( $Value -like "*.*" ) { $DNSAssignment = "Static" }
        ELSE { $DNSAssignment = "" }

        ### Get DNS Suffix
        $DNSSuffix = (Get-DNSClient -InterfaceIndex $NetAdapter.ifIndex -ErrorAction SilentlyContinue).ConnectionSpecificSuffix

        ### Global DNS Suffix
        $InheritedDNSSuffix = (Get-DnsClientGlobalSetting).SuffixSearchList

        ### Get NetConnection Profile
        $NetConnectionProfile = (Get-NetConnectionProfile -InterfaceIndex $NetAdapter.ifIndex -ErrorAction SilentlyContinue).NetworkCategory

        ### Get DNS Server
        $DNSServers = (Get-DnsClientServerAddress -InterfaceIndex $NetAdapter.ifIndex -AddressFamily "IPv4" -ErrorAction SilentlyContinue).ServerAddresses
        IF ($DNSServers.Length -eq 0) { $DNSServers = "$None" }

        ### Get Adapter Type
        
        IF ($Null -eq $IPAddress) { continue }
        ELSEIF ($NetAdapter.PhysicalMediaType -like "*802.11*" -and ((Test-IsPrivateIP $IPAddress) -or $NetAdapter.Status -eq "Disconnected" )) {
            $Type = "WiFi" 
            $ParentAdapter = $NotApplicable2

            IF ($ConnectionStatus -eq "Connected") {
                $ConnectedSSID = netsh wlan show interfaces | select-string -Pattern "[\s]SSID"
                $ConnectedSSID = $ConnectedSSID.tostring().replace(" SSID : ","")

                $Protocol = netsh wlan show interfaces | select-string -Pattern "[\s]Radio Type"
                $Protocol = $Protocol.tostring().replace(" Radio type : ","")

                $SignalStrength = netsh wlan show interfaces | select-string -Pattern "[\s]Signal"
                $SignalStrength = $SignalStrength.tostring().replace(" Signal : ","")

                $LinkSpeed = ([int]($NetAdapter.ReceiveLinkSpeed / 1000000)).ToString()+"\"+([int]($NetAdapter.TransmitLinkSpeed / 1000000)).ToString()
            }
            ELSE {
                $ConnectedSSID = ""
                $Protocol = ""
                $SignalStrength = ""
                $LinkSpeed = ""
            }
        }
        ELSEIF ($NetAdapter.PhysicalMediaType -like "*802.3*" -and ((Test-IsPrivateIP $IPAddress) -or $NetAdapter.Status -eq "Disconnected" )) {
            $Type = "Wired"
            $ParentAdapter = $NotApplicable
            
            IF ($ConnectionStatus -eq "Connected") {
                $ConnectedSSID = $NotApplicable
                $Protocol = "802.3"
                $SignalStrength = $NotApplicable

                $LinkSpeed = ([int]($NetAdapter.ReceiveLinkSpeed / 1000000)).ToString()+"\"+([int]($NetAdapter.TransmitLinkSpeed / 1000000)).ToString()
            }
            ELSE {
                $ConnectedSSID = $NotApplicable
                $Protocol = ""
                $SignalStrength = $NotApplicable
                $LinkSpeed = ""
            }
        }
        ELSEIF ($NetAdapter.ifDesc -like "*Hyper-V*" -and ((Test-IsPrivateIP $IPAddress) -or $NetAdapter.Status -eq "Disconnected" )) {
            $Type = "Hyper-V"

            $vAdapterName = $NetAdapter.Name.Replace("vEthernet (","")
            $vAdapterName = $vAdapterName.Replace(")","")

            TRY { $VMSwitch = Get-VMSwitch -Name $vAdapterName -ErrorAction SilentlyContinue } CATCH {}
            IF ($VMSwitch.NetAdapterInterfaceDescription -ne "" -and $null -ne $VMSwitch.NetAdapterInterfaceDescription) {
                $ParentAdapter = $VMSwitch.NetAdapterInterfaceDescription
                $ParentAdapter = Get-NetAdapter -InterfaceDescription $ParentAdapter -ErrorAction SilentlyContinue
                $ParentAdapter = $ParentAdapter.Name + " ("+$ParentAdapter.InterfaceDescription+")"
            }
            ELSE { $ParentAdapter = "Internal" }
            
            IF ($ConnectionStatus -eq "Connected") {
                $ConnectedSSID = $NotApplicable
                $Protocol = "802.3"
                $SignalStrength = $NotApplicable

                $LinkSpeed = ([int]($NetAdapter.ReceiveLinkSpeed / 1000000)).ToString()+"\"+([int]($NetAdapter.TransmitLinkSpeed / 1000000)).ToString()
            }
            ELSE {
                $ConnectedSSID = $NotApplicable
                $Protocol = ""
                $SignalStrength = $NotApplicable
                $LinkSpeed = ""
            }
        }
        ELSEIF ($NetAdapter.InterfaceDescription -like "*Bluetooth Device*" -and ((Test-IsPrivateIP $IPAddress) -or $NetAdapter.Status -eq "Disconnected" )) {
            $Type = "Bluetooth" 
            $LinkSpeed = ([int]($NetAdapter.ReceiveLinkSpeed / 1000000)).ToString()+"\"+([int]($NetAdapter.TransmitLinkSpeed / 1000000)).ToString()
            TRY { $Protocol = "Bluetooth $(Get-BluetoothVersion)" } CATCH { $Protocol = "" }

        }
        ELSEIF ($NetAdapter.MediaType -eq "IP" -or (Test-IsPrivateIP $IPAddress) -eq $False) {
            $Type = "VPN"  
            $LinkSpeed = ([int]($NetAdapter.ReceiveLinkSpeed / 1000000)).ToString()+"\"+([int]($NetAdapter.TransmitLinkSpeed / 1000000)).ToString()
            $Protocol = "VPN"
        }
        ELSE { continue }
       
        $Results += New-Object PSObject -WarningAction SilentlyContinue -Property @{
            Name = $NetAdapter.Name + " (" + $NetAdapter.DriverDescription + ")"
            Index = $NetAdapter.ifIndex
            Type = $Type
            ParentAdapter = $ParentAdapter
            Protocol = $Protocol
            IPAddress = $IPAddress
            IPAssignment = $IPAsssignment
            DNSServer = $DNSServers
            DNSAssignment = $DNSAssignment
            Status = $ConnectionStatus
            SSID = $ConnectedSSID
            SignalStrength = $SignalStrength
            LinkSpeed = $LinkSpeed
            DNSSuffix = $DNSSuffix
            InheritedDNSSuffix = $InheritedDNSSuffix
            MACAddress = $NetAdapter.MACAddress
            ConnectionProfile = $NetConnectionProfile
        }
    }

    IF($AdapterType -contains "VPN" -or $AdapterType -contains "All") {
        $ActiveAdapters = @()
        $ActiveAdapters += Get-NetAdapter -Physical | Where-Object { $_.Status -eq "Up" }
        $ActiveAdapters += Get-NetAdapter | Where-Object { $_.DriverDescription -like "*Hyper-V*" -and $_.Status -eq "Up" }

        $ActiveConnections = Get-NetIPInterface -ConnectionState Connected -AddressFamily IPv4
    
        FOREACH ($ActiveConnection in $ActiveConnections) {
            IF ($ActiveAdapters.ifindex -contains $ActiveConnection.ifIndex) {}
            ELSEIF ($ActiveConnection.InterfaceAlias -like "*Loopback*" ) {}
            ELSEIF ($ActiveConnection.InterfaceAlias -like "*Psudo*" ) {}
            ELSE {

                $VPNName = $Null
                
                $VPNNAME = (Get-NetAdapter -IfIndex $ActiveConnection.ifIndex -ErrorAction SilentlyContinue).InterfaceDescription
                IF ($Null -eq $VPNName -or $VPNName.Length -eq 0) { $VPNName = (Get-NetAdapter -IfAlias $ActiveConnection.ifAlias -ErrorAction SilentlyContinue).InterfaceDescription  }

                IF ($Null -eq $VPNName -or $VPNName.Length -eq 0) { $VPNName = $ActiveConnection.ifAlias }
                ELSE { $VPNName = $ActiveConnection.ifAlias + " ($VPNNAME)" }


                $Results += New-Object PSObject -WarningAction SilentlyContinue -Property @{
                    Name = $VPNName
                    Index = $ActiveConnection.ifIndex
                    Type = "VPN"
                    ParentAdapter = ""
                    Protocol = ""
                    IPAddress = (Get-NetIPAddress -InterfaceIndex $ActiveConnection.ifIndex -AddressFamily IPv4).IPAddress
                    IPAssignment = ""
                    DNSServer = (Get-DnsClientServerAddress -InterfaceIndex $ActiveConnection.ifIndex -AddressFamily IPv4).ServerAddresses
                    DNSAssignment = ""
                    Status = $ActiveConnection.ConnectionState
                    SSID = ""
                    SignalStrength = "" 
                    LinkSpeed = ""
                    DNSSuffix = (Get-DNSClient -InterfaceIndex $ActiveConnection.ifIndex).ConnectionSpecificSuffix
                    InheritedDNSSuffix = (Get-DnsClientGlobalSetting).SuffixSearchList
                    MACAddress = ""
                    ConnectionProfile = (Get-NetConnectionProfile -InterfaceIndex $ActiveConnection.ifIndex).NetworkCategory
                }
            }
        }
    }

    Write-Progress -ID 7 -Activity "Collecting Adapter Data" -Status "$PercentComplete% - Collecting Data" -PercentComplete 100 -Completed

    $FormattedResults = @()
    $FormattedResults += $Results | Where-Object { $_.Status -eq "Connected" -and $_.Type -eq "Wired" }| Sort-Object -Property Type -Descending
    $FormattedResults += $Results | Where-Object { $_.Status -eq "Connected" -and $_.Type -eq "WiFi" }| Sort-Object -Property Type -Descending
    $FormattedResults += $Results | Where-Object { $_.Status -eq "Connected" -and $_.Type -eq "Hyper-V" }| Sort-Object -Property Type -Descending
    $FormattedResults += $Results | Where-Object { $_.Status -eq "Connected" -and $_.Type -eq "Bluetooth" }| Sort-Object -Property Type -Descending
    $FormattedResults += $Results | Where-Object { $_.Status -eq "Connected" -and $_.Type -eq "VPN" }| Sort-Object -Property Type -Descending
    $FormattedResults += $Results | Where-Object { $_.Status -eq "Disconnected" -and $_.Type -eq "Wired" }| Sort-Object -Property Type -Descending
    $FormattedResults += $Results | Where-Object { $_.Status -eq "Disconnected" -and $_.Type -eq "WiFi" }| Sort-Object -Property Type -Descending
    $FormattedResults += $Results | Where-Object { $_.Status -eq "Disconnected" -and $_.Type -eq "Hyper-V" }| Sort-Object -Property Type -Descending
    $FormattedResults += $Results | Where-Object { $_.Status -eq "Disconnected" -and $_.Type -eq "Bluetooth" }| Sort-Object -Property Type -Descending
    $FormattedResults += $Results | Where-Object { $_.Status -eq "Disconnected" -and $_.Type -eq "VPN" }| Sort-Object -Property Type -Descending

    RETURN $FormattedResults | Select-Object Name, Type, Status, IPAddress, IPAssignment, DNSServer, DNSAssignment, LinkSpeed, Protocol, SignalStrength, SSID, DNSSuffix, InheritedDNSSuffix, ParentAdapter, MACAddress, ConnectionProfile 
}