在不停止程序的情况下处理ADIdentityNotFoundException

时间:2019-06-25 15:31:35

标签: powershell active-directory

我必须为输入文件中的每个对象循环,对每个对象执行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,否则-ErrorAction Stop不会触发捕获,这将导致程序终止意外的结果。

1 个答案:

答案 0 :(得分:0)

我不确定您的程序为什么会终止。使用下面的示例代码循环遍历数组中的所有用户。我故意在数组的第二个值(位置[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"
    }
}

我的输出是

  

找到

     

未找到

     

找到