Search code examples
powershellpowershell-remotingpowershell-7.0

Powershell try/catch validate all test, if one of the test validation failed, it then exits the loop and shows the error?


How to modify the code below so if one of the test validation failed, it then exits the loop and shows the error?

#Test the DNS server functionality, if no errors, generated from the below test, then all is good, exit script.
        try
        {
            $testConnection = Test-Connection $domaincontroller -Count 1
            If (($testConnection -ne "") -or ($testconnection -ne $null))
            {
                Test-DnsServer -IPAddress $ipV4
                Test-DnsServer -IPAddress $ipV4 -Context Forwarder
                Test-DnsServer -IPAddress $ipV4 -Context RootHints
                Test-DnsServer -IPAddress $ipV4 -ZoneName $env:USERDOMAIN
            }
            else
            {
                Write-Host "$computername DNS test failed".
                Exit
            }
        }
        catch
        {
            Write-Output "Exception Type: $($_.Exception.GetType().FullName)"
            Write-Output "Exception Message: $($_.Exception.Message)"
        }

Solution

  • Add -ErrorAction Stop to your commands. It will "Catch" as soon as one of them fails - anything below that point will not be processed. As noted above your If...Then statement is largely redundant:

    Try {
        $testConnection = Test-Connection $domaincontroller -Count 1 -ErrorAction Stop
        Test-DnsServer -IPAddress $ipV4 -ErrorAction Stop
        Test-DnsServer -IPAddress $ipV4 -Context Forwarder -ErrorAction Stop
        Test-DnsServer -IPAddress $ipV4 -Context RootHints -ErrorAction Stop
        Test-DnsServer -IPAddress $ipV4 -ZoneName $env:USERDOMAIN -ErrorAction Stop
    {
    Catch {
        Write-Output $testConnection
        Write-Output "Exception Type: $($_.Exception.GetType().FullName)"
        Write-Output "Exception Message: $($_.Exception.Message)"
    }