0

I am a powershell newbie. I wrote this little script to find the DNS entries of my server list. When I run with several computernames, It is working fine without any issues. When it handles an invalid hostname, it is being caught by the catch block but the script just terminates instead of continuing with the next hostname. What am I doing wrong here?

function Resolve-Hostname
{
[CmdletBinding()]
Param
(
    # One or more compternames
    [Parameter(Mandatory=$true,
               ValueFromPipelineByPropertyName=$true,
               Position=0)]
    [string[]]$Computername
)

Begin
{
    $dns = Get-WmiObject win32_networkadapterconfiguration | Where-Object {$_.DNSHostname -ne $null} |  Select-Object DNS
    Write-verbose "DNS suffix order used -"
    $DNSDomainSuffixSearchOrder = $dns | Select-Object DNSDomainSuffixSearchOrder
    Write-Verbose ( $DNSDomainSuffixSearchOrder | ft -AutoSize | Out-String )
    Write-Verbose "DNS Servers order used -"
    $DNSServerSearchOrder = $dns | Select-Object -ExpandProperty DNSServerSearchOrder
    Write-Verbose ($DNSServerSearchOrder | Out-String )
}
Process
{
    try 
    {
        foreach ($computer in $Computername)
        {
            $dnsreport = [System.Net.Dns]::Resolve("$computer") 
            $dns = [pscustomobject]@{
                Hostname    = $computer
                DNS_Suffix  = $dnsreport.HostName.Split('.',2)[1]
                DNSHostname = $dnsreport.HostName
                IPAddress   = $dnsreport.AddressList.ipaddresstostring -join ", "
                Alias       = $dnsreport.Aliases
            }
            $dns
        }
    }
    catch
    {
        $dns = [pscustomobject]@{
                Hostname    = $computer
                DNS_Suffix  = '-'
                DNSHostname = '-'
                IPAddress   = '-'
                Alias       = '-'
        }
        $dns
    }
}
End
{
}
}

1 Answer 1

2

Your foreach is inside the try block, so when an exception occurs, it goes to the catch block which is outside the loop. Put both the try and the catch inside the foreach loop.

Sign up to request clarification or add additional context in comments.

1 Comment

Silly me. I should learn to think simple. Thank you Briantist :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.