I'm trying to get the IPv4 address of interfaces that are connected in PowerShell, so I tried this :
Get-NetIPAddress -AddressFamily IPv4 | select InterfaceAlias , IPAddress | Sort-Object InterfaceAlias
But I noticed it output more interfaces than expected so I tried this :
PS C:\> Get-NetIPInterface -ConnectionState Connected | % { Get-NetIPAddress -AddressFamily IPv4 -InterfaceAlias $_.InterfaceAlias } | select InterfaceAlias , IPAddress
InterfaceAlias IPAddress
-------------- ---------
WiFi 192.168.1.145
Loopback Pseudo-Interface 1 127.0.0.1
WiFi 192.168.1.145
Loopback Pseudo-Interface 1 127.0.0.1
PS C:\>
But then I see twice the same lines.
I expected this result :
InterfaceAlias IPAddress
-------------- ---------
WiFi 192.168.1.145
Loopback Pseudo-Interface 1 127.0.0.1
PS C:\>
How can this be done ?
Olaf has provided the solution in a comment; let me elaborate:
Get-NetIPInterface
itself allows filtering the interfaces by address family via its -AddressFamily
parameter.
The filtered interfaces can directly be passed to Get-NetIPAddress
via the pipeline.
The latter offers several pipeline-binding parameters, but with Get-NetIPInterface
output, it is the .InterfaceAlias
property of the latter's output objects that binds to the former's -InterfaceAlias
parameter.
See this answer for how to inspect a given command's pipeline-binding parameters, optionally also programmatically.
Therefore:
Get-NetIPInterface -ConnectionState Connected -AddressFamily IPv4 |
Get-NetIPAddress |
Select-Object InterfaceAlias, IPAddress |
Sort-Object InterfaceAlias