1

I need to write a powershell scripts that uses the same property name but from two differents sources. Something a bit similar to such SQL clause "Select UserID from Users,AD where Users.UserID = AD.UserID"

I have this code to retrieve all interface names that are connected to a network.

$allitf = Get-NetIPInterface -AddressFamily IPv4 -ConnectionState "Connected" | Select-Object -Property InterfaceAlias

So at this point $allitf contains several items with one or more "InterfaceAlias".

Now for each item, I want to get the IP address of that interface, so I would run something like:

foreach ($itf in $allitf) { Get-NetIPAddress | Where-Object { $_.InterfaceAlias -eq $itf } }

but this returns no items. And I cannot use:

foreach ($itf in $allitf) { Get-NetIPAddress | Where-Object { $_.InterfaceAlias -eq $_.InterfaceAlias } }

The first occurence of $_.InterfaceAlias would represent the property of Get-NetIPAddress result, the second occurence should be filled with the property of $itf.

Alternatively, it could be written like this, but the problem remains.

$allitf | ForEAch-Object { Get-NetIPAddress | Where-Object { $_.InterfaceAlias -eq $_.InterfaceAlias } }

How to write a proper "where clause" here?

Solutions

  1. As Santiago Squarzon suggested, this works:
Get-NetIPInterface -AddressFamily IPv4 -ConnectionState "Connected" | Get-NetIPAddress

I just wanted to avoid yet another pipe :-D because I have some more in my full line code.

  1. Suggestion from zett42 gives this solution:
$allitf = Get-NetIPInterface -AddressFamily IPv4 -ConnectionState "Connected" | Select-Object -ExpandProperty InterfaceAlias

foreach ($itf in $allitf) { Get-NetIPAddress | Where-Object { $_.InterfaceAlias -eq $itf } }

Thanks to both of you.

  • 3
    Why not just pipe them? `Get-NetIPInterface -AddressFamily IPv4 -ConnectionState 'Connected' | Get-NetIPAddress` – Santiago Squarzon Jun 03 '23 at 21:23
  • 2
    The problem with your code is, that `Select-Object -Property InterfaceAlias` outputs an object with a single property, not the property value itself. This would be fixed by replacing `-Property` by `-ExpandProperty` or using `ForEach-Object InterfaceAlias` instead of `Select-Object`. But you should really do piping like Santiago wrote. – zett42 Jun 03 '23 at 21:58
  • In short: [`Select-Object`](https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/select-object) (`select`) by default returns _a `[pscustomobject]` instance_ that has the _requested properties_ - even when you're only asking for a _single_ property. To get only that property's _value_, use the `-ExpandProperty` parameter instead of the (possibly positionally implied) `-Property` parameter. See the linked duplicate for details and alternatives, notably the ability to simply use `(...).SomeProperty` – mklement0 Jun 04 '23 at 12:51

0 Answers0