Reputation: 9856
I am making writing a Powershell
script that have to automize the initial set-up of a windows machine. For some of the operations I'm gonna need the machine IP but since we are part of a large group (not sure about the terminology) and there's a chance that at some point the same hostname may be associated with 2 or more IP's I want to get all IPv4 IP addresses and based on the result (if there is only 1 on multiple) to write some logic.
Right now I have this:
$ips = [System.Net.Dns]::GetHostAddresses("myhostname")
but when I execute $ips.Count
right after I get 2
and when I do the following:
[System.Net.Dns]::GetHostAddresses("myhostname") | foreach {echo $_.IPAddressToString }
it turns out that I got the IPv4 and (almost) IPv6 addresses.
If I am sure this will always be the case it's OK, but since I want to check for multiple IPv4 addresses and I don't need the IPv6 at all how can I take only the IPv4 ones and check theirs count?
Upvotes: 0
Views: 6760
Reputation: 200193
Filter the result of the GetHostAddresses()
call by address family. IPv4 addresses have the address family InterNetwork
while IPv6 addresses have the address family InterNetworkV6
.
$ips = [Net.Dns]::GetHostAddresses('myhostname') |
Where-Object { $_.AddressFamily -eq 'InterNetwork' } |
Select-Object -Expand IPAddressToString
@($ips).Count
Upvotes: 6