'Why Powershell output all items in collection ignorig IF statement?

This code supposed to output only macaddress of active connection, yet it output all macaddresses of all PhysicalAdapters

# Assign info on Network Connections selected fileds to collection
$q = Get-CIMInstance Win32_NetworkAdapter | Select-Object NetConnectionStatus, PhysicalAdapter, MACAddress
 
# Find mac address of active connection
foreach ($i in $q) {IF ($q.NetConnectionStatus -eq 2) {Write-Host $i.MacAddress}}

In output I recieve all macaddresses of all physical adapters.



Solution 1:[1]

You have a typo on your if condition, $q is the collection not the item ($i):

IF ($q.NetConnectionStatus -eq 2)

Since -eq can act as a filter when the left-hand side of the operation, as long as there is at least one element in $q.NetConnectionStatus equal to 2, the condition will be $true hence all items are being outputted to the console.

Try this simple example to understand what is happening:

$collection = 0..10 | ForEach-Object {
    [pscustomobject]@{
        NetConnectionStatus = $_
        MACAddress = Get-Random
    }
}
foreach($item in $collection) {
    if($collection.NetConnectionStatus -eq 2) {
        $item.MACAddress
    }
}

This will output 11 random numbers to your console. The right filtering condition on above example should have been:

if($item.NetConnectionStatus -eq 2) {

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1