pizzim13
pizzim13

Reputation: 1482

PowerShell: Format Get-WmiObject output to return only the IP address

I would like to use Get-WmiObject Win32_NetworkAdapterConfiguration to return the ip address of a network card. Unfortunately, I cannot figure out how to format the output to display only the IPv.4 address.

Get-WmiObject Win32_NetworkAdapterConfiguration | Select IPAddress | Where-Object {$_.IPaddress -like "192.168*"}

Displays:

IPAddress
---------
{192.168.56.1, fe80::8980:15f4:e2f4:aeca}

Using the above output as an example, I would like it to only return 192.168.56.1 (Some clients have multiple NIC's, hence the "Where-Object")

Upvotes: 6

Views: 54409

Answers (6)

Djily Bakhdad
Djily Bakhdad

Reputation: 1

(Get-WMIObject -Class Win32_NetworkAdapterConfiguration).IPAddress

Upvotes: 0

Molotok
Molotok

Reputation: 11

(Get-WmiObject Win32_NetworkAdapterConfiguration | where { (($_.IPEnabled -ne $null) -and ($_.DefaultIPGateway -ne $null)) } | select IPAddress -First 1).IPAddress[0]

Returns the IP-address of network connection with default gateway. This is exactly what you need in most cases :)

Compatible with Powershell 2.0 (Windows XP) and newer.

Upvotes: 1

Start-Automating
Start-Automating

Reputation: 8367

Adding a quicker answer (avoiding Where-Object and using -like operation on a list):

@(@(Get-WmiObject Win32_NetworkAdapterConfiguration | Select-Object -ExpandProperty IPAddress) -like "*.*")[0]

Hope this Helps

Upvotes: 4

Chris
Chris

Reputation: 1

(Get-WmiObject win32_Networkadapterconfiguration | Where-Object{$_.ipaddress -notlike $null}).IPaddress | Select-Object -First 1

Hope that this will help !

Upvotes: 0

Steve
Steve

Reputation: 11

Thought I would share my own variation on the above, in case it helps someone. Just one line:

Get-WmiObject win32_networkadapterconfiguration | where { $_.ipaddress -like "1*" } | select -ExpandProperty ipaddress | select -First 1

Cheers.

Upvotes: 1

Joey
Joey

Reputation: 354406

The IPAddress property is a string[], so the following should do it:

gwmi Win32_NetworkAdapterConfiguration |
    Where { $_.IPAddress } | # filter the objects where an address actually exists
    Select -Expand IPAddress | # retrieve only the property *value*
    Where { $_ -like '192.168.*' }

Upvotes: 10

Related Questions