![](/img/trans.png)
[英]Unable to catch the exception in try/catch statement in powershell
[英]Catch error and restart the if statement
我有一个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 {...}
由于以下错误,无法在目标计算机(“计算机名称”)上执行此命令:指定的域不存在或无法联系。
您可以使用内置的$ Error变量。 在执行代码之前将其清除,然后测试后错误代码的计数是否大于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}
}
您可以设置一个函数在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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.