Get IP Addresses with PowerShell

In celebration of World IPv6 Day, I thought I’d post a little PowerShell code to return IP addresses for a computer. This information is stored in WMI with the Win32_NetworkAdapterConfiguration class. This class will return information about a number of virtual adapters as well so I find it easier to filter on the IPEnabled property.

The returned object has an IPAddress property which is an array of addresses. In here you will find IPv4 and IPv6 addresses. My quick and dirty script uses a relatively simple regular expression pattern to get those addresses.

Param([string]$computername=$env:computername)

[regex]$ip4="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"

get-wmiobject win32_networkadapterconfiguration -filter "IPEnabled='True'" -computer $computername |
 Select DNSHostname,Index,Description,@{Name="IPv4";Expression={ $_.IPAddress -match $ip4}},
 @{Name="IPv6";Expression={ $_.IPAddress -notmatch $ip4}},MACAddress

In the Select-Object expression I’m defining custom properties to get the different IP addresses. Here’s what it looks like in action.

PS E:\> C:\scripts\Get-IP.ps1 -comp quark

DNSHostname : Quark
Index       : 10
Description : Realtek PCIe FE Family Controller
IPv4        : 172.16.10.126
IPv6        : fe80::ddcf:c714:44c8:bcc3
MACAddress  : C8:0A:A9:04:C5:32

If you had a number of computers you could pipe the results to Where-Object and get just the IPv6 machines (or not).

... | where {$_.Ipv6} | Sort DNSHostname | Select DNSHostname,Description,IPv6

Feel free to download Get-IP and try it out for yourself.

Post to Twitter Post to Plurk Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to FriendFeed Post to Google Buzz Post to Ping.fm Post to Reddit Post to Slashdot Post to StumbleUpon Post to Technorati


About the Author

PowerShell.org Announcer

This is the official account for PowerShell.org and sponsor announcements.