【问题标题】:handle ADIdentityNotFoundException without stopping the program在不停止程序的情况下处理 ADIdentityNotFoundException
【发布时间】: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


【解决方案1】:

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

我的输出是

找到

找不到

找到

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    相关资源
    最近更新 更多