首页 > 解决方案 > 在不停止程序的情况下处理 ADIdentityNotFoundException

问题描述

我必须循环输入文件中的每个对象,对每个对象执行 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,这将导致程序终止的不良结果。

标签: powershellactive-directory

解决方案


我不确定你的程序为什么会终止。使用下面的示例代码循环遍历数组中的所有用户。我故意在数组的第二个值(位置 [1])中输入了不正确的用户名:

$users = "username1", "username2", "username3" #username2 is purposely incorrect
foreach ($i in $users){
    try{
        $user = Get-ADUser -Identity $i -Properties * -ErrorAction Stop
        Write-Host "Found"
    }catch{
        Write-Host "Not found"
    }
}

我的输出是

成立

未找到

成立


推荐阅读