我有一个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')上执行此命令:指定的域不存在或无法联系。
答案 0 :(得分:1)
您可以使用内置的$ Error变量。在执行代码之前清除它,然后测试错误代码的计数是否为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}
}
答案 1 :(得分:0)
您可以设置一个功能来在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
}
}