12

I want to retrieve IP Addresses from computer names but I ONLY want the IP nothing more.

$computer = 'Server1'
$computer = [System.Net.Dns]::GetHostAddresses($computer) | select IPAddressToString

Returns @{IPAddressToString=x.x.x.x}. How do I return 'x.x.x.x'

Delonte Johnson
  • 341
  • 2
  • 4
  • 13

4 Answers4

12

Replace

| select IPAddressToString

With (Powershell 2.0+)

| select -First 1 -ExpandProperty IPAddressToString

Or, in the case where you want to work with an array

| select -ExpandProperty IPAddressToString

This will give you an array of strings, so if you want individual addresses, use something like

([System.Net.Dns]::GetHostAddresses($computer) | select -ExpandProperty IPAddressToString)[0]
Greenstone Walker
  • 779
  • 1
  • 5
  • 16
  • `-select -ExpandProperty Text` also worked for me when getting the inner text value (as opposed to the `@{Text=}` format) of a RadioButton whose declaration and whose Text values were all created programmatically from a function and an array, respectively. The missing piece was using `Select -ExpandProperty Text` instead of `Select-Object Text`. – TylerH Mar 01 '19 at 21:50
7

Using your example, you'd type $Computer.IPAddressToString to return the array of IP addresses. If there is only 1 IP address for that hostname, then that's all there is. However, a hostname may have many addresses, and that's why it's an array. So if you only want to see the first IP address in the array, you could type $Computer.IPAddressToString[0]

Ryan Ries
  • 55,481
  • 10
  • 142
  • 199
1

add ().IpAddressToString

([Net.Dns]::GetHostAddresses('Server1')).IpAddressToString
Rm558
  • 111
  • 3
0

I do it this way all the time with foreach, as opposed to select -expand:

$computer = 'Server1'
$computer = [Net.Dns]::GetHostAddresses($computer) | foreach IPAddressToString
js2010
  • 173
  • 4