【问题标题】:Catch error and restart the if statement捕获错误并重新启动 if 语句
【发布时间】:2015-04-25 05:42:02
【问题描述】:

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

谢谢!


代码:

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')上执行:指定的域不存在或无法联系。

【问题讨论】:

    标签: powershell error-handling try-catch catch-block


    【解决方案1】:

    您可以使用内置的 $Error 变量。在执行代码之前清除它,然后测试 post error code 的计数是否为 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}
    }
    

    【讨论】:

    • 这实际上以我希望的方式为我工作!谢谢!
    【解决方案2】:

    您可以设置一个函数在 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
            }
        }
    

    【讨论】:

    • 我认为你需要为 try catch 添加-ErrorAction Stop。我不认为这是一个终止错误。
    • 非常感谢!我知道有一种方法可以使用 try-catch 方法!
    • 第一个例子:添加参数:Add-ComputerToAD -Domain $Domain 第二个,使用do/while。因为 while() 永远不会调用 Add-Computer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2017-04-28
    相关资源
    最近更新 更多