Powershell try/catch 验证所有测试,如果其中一个测试验证失败,则退出循环并显示错误?

Powershell try/catch validate all test, 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)"
        }

-ErrorAction Stop 添加到您的命令中。一旦其中一个失败,它就会“捕捉”——低于该点的任何东西都不会被处理。如上所述,您的 If...Then 语句在很大程度上是多余的:

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)"
}