Question:
I am using Get-NetIPAddress. ALL I want is the actual address without ANY formatting or tables or anything.
If I use
1 2 |
(Get-NetIPAddress).IPAddres |
I get a list of addresses for all ports. I want only a single port so I tried to pipe it but gave nothing in return:
1 2 |
(Get-NetIPAddress).IPv4Address | Where-Object InterfaceAlias -eq "MyPortName" |
But if I do this:
1 2 |
Get-NetIPAddress.IPv4Address | Where-Object InterfaceAlias -eq "MyPortName" |
It says that this is an invalid command.
If I use this:
1 2 |
Get-NetIPAddress | Where-Object InterfaceAlias -eq "MyPortName" | Where-Object AddressFamily -eq IPv4 | Select-Object IPAddress |
I get:
1 2 3 4 |
IPAddress --------- 10.45.22.100 |
So what is going on when I put parenthesis around Get-NetIPAddress and how can I get JUST the darn address number for a particular port?
Answer:
Brackets work in the same way as they do in mathematics, they set an order of precedence, so anything within brackets will execute first.
To get just the IP Address value from your final command, do this instead:
1 2 |
(Get-NetIPAddress | Where-Object InterfaceAlias -eq "MyPortName" | Where-Object AddressFamily -eq IPv4).IPAddress |
This command:
1 2 |
(Get-NetIPAddress).IPv4Address |
Returns the value of the IPv4Address
property (probably as a string), which is why this command then doesn’t work:
1 2 |
(Get-NetIPAddress).IPv4Address | Where-Object InterfaceAlias -eq "MyPortName" |
As you are piping a string object that contains an IP Address into the Where-Object
cmdlet and then are looking to filter on the InterfaceAlias
property that does not exist in that object.
When you access a property via the .
notation you get it’s value. When you access a property via the Select-Object
cmdlet you return an object (of the same type as the source object) that is filtered down to just containing that single property (unless you use the -ExpandProperty
switch, which causes Select-Object
to return the value of the defined property instead of an object in the same way as using .
notation).
Long story short, do any filtering you need to do first, then access the property/properties you want as a result last.