Bulk-Convert to String

by May 17, 2016

Sometimes, commands and methods do not return exactly what you are after. If you, for example, wanted to get the assigned IP addresses for a hostname, you could try this:

[System.Net.DNS]::GetHostByName('microsoft.com').AddressList

You do get the IP addresses, but they are part of a larger object. The result looks like this:

 
Address            : 601041000
AddressFamily      : InterNetwork
ScopeId            : 
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 104.40.211.35

(...)

Address            : 4223871848
AddressFamily      : InterNetwork
ScopeId            : 
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 104.43.195.251 

If you convert the output to a string, however, you get what you want:

[System.Net.DNS]::GetHostByName('microsoft.com').AddressList | 
ForEach-Object { "$_" }

Converting objects to strings can be a last resort if you can’t see another way of getting to the information you are after. The result now looks like this:

 
104.40.211.35
191.239.213.197
23.96.52.53
23.100.122.175
104.43.195.251 

And here are the two power tips: if you get too much data from a command, identify the name of the information you are after, and add this with a “.”. So you can get to the IP addresses much more elegantly like this:

[System.Net.DNS]::GetHostByName('microsoft.com').AddressList.IPAddressToString

(The latter technique may require at least PowerShell 3.0, though).

If you must convert all elements to a string, rather than adding a cumbersome ForEach-Object loop, “abuse” the -replace operator like this:

[System.Net.DNS]::GetHostByName('microsoft.com').AddressList -replace ''

The operator does not replace anything. It just converts all incoming data into strings.

Twitter This Tip! ReTweet this Tip!