Powershell DirectoryService object error neither caught nor trapped

后端 未结 2 1504
长发绾君心
长发绾君心 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: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"
    }
    

提交回复
热议问题