Powershell DirectoryService object error neither caught nor trapped

后端 未结 2 1489
长发绾君心
长发绾君心 2021-01-22 17:22

This is part of my script:

Trap {Write-Output \'Authentication Error trapped\'}
Try {New-Object System.DirectoryServices.DirectoryEntry $strDistinguishedName,$st         


        
相关标签:
2条回答
  • 2021-01-22 17:29

    I had a similar error and the comment from @TessellatingHeckler helped me. Piping the result to Out-Null fixed it for me. So you can try the following:

    Trap {Write-Output 'Authentication Error trapped'}
    Try {New-Object System.DirectoryServices.DirectoryEntry $strDistinguishedName,$strUsername,$strPlainPassword -ErrorAction stop | Out-Null}
    Catch{Write-Output 'Authentication Error catched'}
    Write-Output 'Script has not trapped nor catched the error but continued'
    
    0 讨论(0)
  • 2021-01-22 17:38

    I've recently come up against the same error, trying to instantiate a DirectoryEntry object to RootDSE on a domain where there is no trust with the current domain. What I found is that calling a method on the resulting object allows the exception to be successfully trapped/caught.

    So this doesn't work as might be expected:

    try 
    {
        $RDSE = [adsi]"LDAP://UntrustedService/RootDSE"
    }
    catch
    {
        Write-Warning "Unable to connect to service"
    }
    

    But this does:

    try 
    {
        $RDSE=[adsi]"LDAP://UntrustedService/RootDSE"
        [void]$RDSE.ToString()
    }
    catch [System.Management.Automation.RuntimeException]
    {
        Write-Warning "Unable to connect to service"
    }
    catch #Default
    {
        Write-Warning "Some other error"
    }
    
    0 讨论(0)
提交回复
热议问题