Wednesday, 13 January 2016

PowerShell: List all IPv4 Addresses

A very short blog post today. I'm not sure why this is so complicated, maybe there's an easier way, or a more recent cmdlet that allows it to be obtained in an easier way.

I want to list all IP (v4) addresses and nothing else with a single line PowerShell command that is backwards compatible with all versions of PowerShell.

Here's what I came up with:

foreach ( $i in (Get-WmiObject Win32_NetworkAdapterConfiguration -Namespace "root\CIMV2" | where { $_.IPEnabled -eq "True" } | select IPAddress) ) { $i.IPAddress[0] }

Here's a quick breakdown of the command

It's basic structure uses a foreach loop

Foreach ( $TempVariable in $MyVariableList ) { do this }

$i is my temporary variable, that exists only for the purposes of the loop. The Foreach loop will cycle through each object in the second variable, and each time it will be represented by $i

$MyVariableList is a variable that contains many objects, and is often obtained in a script by a separate command. As I want a one-liner, I have substituted this variable with a command that produces a list of objects.

This is my command:

Get-WmiObject Win32_NetworkAdapterConfiguration -Namespace "root\CIMV2" | where { $_.IPEnabled -eq "True" } | select IPAddress)

It uses Get-WMIObject to return the WMI class Win32_NetworkAdapterConfiguration. I chose the Get-WMIObject command to return the IP address data because I know it is compatible with all version of PowerShell. This command on its own returns a large amount of data, so I have piped the results to the Where-Object command. This filters to return only network adapters that are enabled. These results are then piped to the Select-Object command, and this selects the single property of IP address.


IP Address properties






The result is an IP address object for each adapter. Each contains both an IPv4 and IPv6 address.

{ do this } Finally the Foreach loop will carry out an action on each object that is returned. In this case it simply takes the object and calls the IPAddress property (which is the only one available). The square brackets specify the 1st result only will be displayed.

IP Address list




Simple.




No comments:

Post a Comment