0

如何修改下面的代码,以便如果其中一个测试验证失败,它会退出循环并显示错误?

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

1 回答 1

1

添加-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)"
}
于 2020-07-18T07:07:47.870 回答