Habanagold
Habanagold

Reputation: 51

Force Test-connection to use IPv4

I have a script that tests for hosts using Test-Connection. If successful it proceeds, if not it states the host is offline.

Problem is, our enterprise has IPv6 entries in our DNS zones. Hosts that register in DNS with IPv6 are responding first and since IPv6 isn't in use, Test-Connection states that they are Offline. However, good old fashion ping with the -4 switch works fine and they respond.

I have been looking to find a switch to force Test-Connection to use IPv4, but can't find anything. I can't make massive changes to DNS zones to purge IPv6 records because the host will simply re-register. I don't have control over that.

Ping works fine but I am having trouble with it because I can't get it to return simple TRUE or FALSE.

Upvotes: 1

Views: 9721

Answers (2)

Brian McMahon
Brian McMahon

Reputation: 399

Test-Connection supports an -IPV4 switch to force IPV4 with PowerShell 7. I'm not sure when this functionality was added.

However, Test-Connection for Windows PowerShell apparently does not support the -IPV4 switch to this day.

Someday the schism will be resolved.

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200453

Run ping and check the $LASTEXITCODE automatic variable:

& ping -4 -n 1 $server >$null
if ($LASTEXITCODE -eq 0) {
    'success'
} else {
    "$server not accessible"
}

You could also do a name lookup first, restrict it to IPv4 addresses (A records only), and run Test-Connection on the IPv4 address:

$ip = & nslookup -type=A $server |
      Select-Object -Skip 4 -First 1 |
      ForEach-Object { $_.Split(':')[1].Trim() }

Test-Connection $ip

If you have at least Windows 8 you could use Resolve-DnsName instead of nslookup, which is a little more PoSh:

$ip = Resolve-DnsName -Type A $server |
      Select-Object -Expand IPAddress

Upvotes: 2

Related Questions