捕获错误并重新启动 if 语句

Catch error and restart the if statement

我有一个将计算机添加到域的 powershell 脚本。有时,当我 运行 脚本时出现以下错误,而当我 运行 它第二次运行时。 我如何制作脚本来检查我是否收到此错误,如果是,则重试将其添加到域中? 我读过很难尝试捕获这样的错误。那是对的吗?有没有 better/different 方法来捕获错误?

谢谢!


代码:

if ($localIpAddress -eq $newIP)
        { # Add the computer to the domain
          write-host "Adding computer to my-domain.local.. "
          Add-Computer -DomainName my-domain.local | out-null
        } else {...}

错误:

由于以下错误,无法在目标计算机('computer-name')上执行此命令:指定的域不存在或无法联系。

您可以设置一个函数来在 Catch 上调用自身。类似于:

function Add-ComputerToAD{
Param([String]$Domain="my-domain.local")
    Try{
        Add-Computer -DomainName $Domain | out-null
    }
    Catch{
        Add-ComputerToAD
    }
}

if ($localIpAddress -eq $newIP)
        { # Add the computer to the domain
          write-host "Adding computer to my-domain.local.. "
          Add-ComputerToAD
        } else {...}

老实说,我还没有尝试过,但我不明白为什么它不起作用。它不是特定于该错误的,因此它会无限循环重复错误(即 AD 中已经存在另一台具有相同名称的计算机,或者您指定了无效的域名)。

否则您可以使用 While 循环。像

if ($localIpAddress -eq $newIP)
    { # Add the computer to the domain
        write-host "Adding computer to my-domain.local.. "
        While($Error[0].Exception -match "The specified domain either does not exist or could not be contacted"){
            Add-Computer -DomainName my-domain.local | out-null
        }
    }

您可以使用内置的 $Error 变量。在执行代码之前清除它,然后测试 post 错误代码的计数是否为 gt 0。

$Error.Clear()
Add-Computer -DomainName my-domain.local | out-null
if($Error.count -gt 0){
    Start-Sleep -seconds 5
    Add-Computer -DomainName my-domain.local | out-null}
}