private/Resolve-DNS.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function Resolve-DNS {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Address
    )

    try {
        # Determine the IP
        try {
            $ipAddress = $null
            [System.Net.IPAddress]::TryParse($Address, [ref]$ipAddress) > $null
            # IP
            $Address = $ipAddress.IPAddressToString
        }catch {
            # DNS
            try {
                "Resolving DNS: $Address" | Write-Verbose
                $ipAddresses = [System.Net.Dns]::GetHostAddresses($Address)
                $address = $ipAddresses[0].IPAddressToString
                # $ipAddress = [System.Net.Dns]::GetHostEntry($Address)
                # $ipAddress = [System.Net.Dns]::Resolve($Address)
                # $address = $ipAddress.AddressList[0].IPAddressToString
            }catch {
                throw "Failed to resolve DNS: $Address"
            }
        }
    }catch {
        if ($ErrorActionPreference -eq 'Stop') {
            throw
        }else {
            Write-Error -ErrorRecord $_
        }
    }
    $Address
}