1

I'm using the following to get the IP address of a web service:

$o = [System.Net.Dns]::GetHostAddresses("myservice.domain.com")
$o   correctly returns the object properties.

Address           : **********
AddressFamily     : InterNetwork
ScopeId           : 
IsIPv6Multicast   : False
IsIPv6LinkLocal   : False
IsIPv6SiteLocal   : False
IPAddressToString : 10.0.0.1

But if I do:

$o.IPAddressToString

Nothing is returned.

IPAddressToString is a ScriptProperty.

I need to get the IP address to feed into another script. How can I do this?

3 Answers 3

3

Give this a try:

$o[0].IPAddressToString

Or

$o[0].ToString()

The GetHostAddresses -- Note the last "s", making it plural. You get back an array containing the IP(s) of the host. If you need to iterate the entire array of addresses you can do the following:

foreach ($i in $o) { $i.IPAddressToString }

See this MSDN for more details Dns.GetHostAddresses Method (System.Net)

2
  • This option is more succinct. Really appreciate the assist! Feb 6, 2012 at 20:52
  • Agreed. updated my answer Feb 6, 2012 at 21:01
1

I know this is old but this is a working one liner

$ipAddy = [System.Net.Dns]::GetHostAddresses("yahoo.com")[0].IPAddressToString;
0

Expand the ScriptProperty to access the output value:

$IpAddress = [System.Net.Dns]::GetHostAddresses("www.example.com") | select IPAddressToString -ExpandProperty IPAddressToString

Be aware that if the GetHostAddresses() medthod returns more than one IPAddress object, $IPAddress will contain multiple strings, so the safe way is either to either enumerate and return all IP Addresses as strings individually, or pick the first one:

$IpAddress = ([System.Net.Dns]::GetHostAddresses("www.example.com"))[0]

like in jscott's suggestion

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.