As a Powershell beginner I misunderstand some behavior of the boolena logic operatorr “-and”.
I’m developing a simple script that does something depending on current active status of my laptop and network setting: Lapop: so wired (ethernet or not (wi-fi), on power or on battery and is it at my home (where my NAS is as well) or is it in the office of my (volunteer-)work (other ip-address).
So I tried a lot and I have a simple straight forward solution to that, but during development I stumbled upon a – in my opinion strange – behavior and I’m looking for an explanation.
Situation:
All interfaces on my laptop:
PS C:\> Get-NetIPAddress -AddressFamily IPv4 | select -Property ipaddress, interfacealias
ipaddress interfacealias
--------- --------------
192.168.1.118 Ethernet 4
172.22.32.1 vEthernet (Default Switch)
192.168.1.116 Ethernet 2
169.254.31.247 Local Area Connection* 2
169.254.84.130 Bluetooth Network Connection
169.254.171.204 Local Area Connection* 1
192.168.1.117 Wi-Fi
127.0.0.1 Loopback Pseudo-Interface 1
This command below + output is OK for me:
PS C:\> Get-NetIPAddress -AddressFamily ipv4 | where {$_.InterfaceAlias -eq "Wi-Fi" -or $_.InterfaceAlias -like "Ethernet*"} | Select -Property ipaddress, interfacealias
ipaddress interfacealias
--------- --------------
192.168.1.118 Ethernet 4
192.168.1.116 Ethernet 2
169.254.230.159 Wi-Fi
This as well:
PS C:\> Get-NetIPAddress -AddressFamily ipv4 | where {$_.IPv4Address -like "192.168.1.11[6,8]"} | select -Property ipaddress
ipaddress
---------
192.168.1.118
192.168.1.116
But combining the 2 critera with a boolean -and results in a for me unexpected output:
PS C:\> Get-NetIPAddress -AddressFamily ipv4 | where {{$_.InterfaceAlias -eq "Wi-Fi" -or $_.InterfaceAlias -like "Ethernet*"} **-and** {$_.IPAddress -like "192.168.1.11[6,8]"}} | Select -Property ipaddress, interfacealias
ipaddress interfacealias
--------- --------------
172.22.32.1 vEthernet (Default Switch)
192.168.1.116 Ethernet 2
169.254.31.247 Local Area Connection* 2
169.254.84.130 Bluetooth Network Connection
169.254.171.204 Local Area Connection* 1
169.254.230.159 Wi-Fi
127.0.0.1 Loopback Pseudo-Interface 1
I think “and-ing” 2 criteria should not extend the results, but should deliver less results (not for this combination, but in general).
Please can you explain this to me? What is wrong with my perception of this?
Kind regards,
Hans Troost