Separating IPv4 and IPv6

by Feb 10, 2020

Let’s assume you want to return IP addresses from all network cards but separate them by address type. Here is an approach that uses solely Select-Object:

function Get-IPAddress
{
  Get-CimInstance -ClassName Win32_NetworkAdapterConfiguration |
  Where-Object { $_.IPEnabled -eq $true } |
  # add two new properties for IPv4 and IPv6 at the end
  Select-Object -Property Description, MacAddress, IPAddress, IPAddressV4, IPAddressV6 |
  ForEach-Object {
    # add IP addresses that match the filter to the new properties
    $_.IPAddressV4 = $_.IPAddress | Where-Object { $_ -like '*.*.*.*' }
    $_.IPAddressV6 = $_.IPAddress | Where-Object { $_ -notlike '*.*.*.*' }
    # return the object
    $_
  } |
  # remove the property that holds all IP addresses
  Select-Object -Property Description, MacAddress, IPAddressV4, IPAddressV6 
}

Get-IPAddress

The result looks similar to this:

 
Description                          MacAddress        IPAddressV4   IPAddressV6             
-----------                          ----------        -----------   -----------             
Realtek USB GbE Family Controller #3 00:E0:4C:F4:A9:35 10.4.121.75   fe80::8109:a41e:192b:367 
 


You are a PowerShell Professional, passionate about improving your code and skills? You take security seriously and are always looking for the latest advice and guidance to make your code more secure and faster? You’d love to connect to the vibrant PowerShell community and get in touch with other PowerShell Professionals to share tricks and experience? Then PowerShell Conference EU 2020 might be just the right place for you: https://psconf.eu (June 2-5, 2020 in Hanover, Germany).

It’s a unique mixture of classic conference with three parallel tracks filled with fast-paced PowerShell presentations, and advanced learning class with live discussions, Q&A and plenty of networking.

Secure your seat while they last: https://psconf.eu/register.html.

Twitter This Tip! ReTweet this Tip!