【发布时间】:2019-06-25 23:43:58
【问题描述】:
我必须循环输入文件中的每个对象,对每个对象执行 Get-ADUser,并且我想在不停止循环的情况下处理 ADIdentityNotFoundException 错误。有没有更好的方法可以做到这一点(例如为了简化):
Import-Csv $input | Foreach-Object {
$manager = "BLANK"
if ($user = Get-ADUser $_."samaccountname" -properties * ) {
# I don't think I need this in an IF{} since the line below won't work
# so $manager will be equal to the last value set, "BLANK", but
# this makes it easier to understand what I want to happen
$manager = $user."manager"
# I need more properties (thus -properties *) but again just an example
}
}
本质上,如果Get-ADUser查找成功,则设置$manager = $user."manager"
如果不成功,不要停止循环,不要复制前一个用户的值,有$manager = "BLANK"(或其他)。我对 try/catch 解决方案的问题是 ADIdentityNotFoundException 不会触发 catch,除非我添加 -ErrorAction Stop,这将导致程序终止的不良结果。
【问题讨论】:
-
请仔细阅读
try/catch/finally结构文档。它旨在让您具体控制如何处理错误 - 终止错误 在 try 块中 将触发catch块 - 它不会终止程序..
标签: powershell active-directory