Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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)

share|improve this answer
    
This option is more succinct. Really appreciate the assist! –  Greg Oliver Feb 6 '12 at 20:52
    
Agreed. updated my answer –  Mathias R. Jessen Feb 6 '12 at 21:01

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

share|improve this answer
    
Thanks so much, Mathias! –  Greg Oliver Feb 6 '12 at 20:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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