如何通过PowerShell处理Active Directory异常?

时间:2018-04-29 19:07:12

标签: powershell

我在使用ActiveDirectoryObjectNotFoundException方法时尝试在PowerShell中处理Forest.GetForest异常。

https://msdn.microsoft.com/en-us/library/system.directoryservices.activedirectory.forest.getforest(v=vs.110).aspx

# Clear screen 
Clear

# Change below as per your requirements

$context='forest'
$name='My.Lab.Local'
$username="fake\Administrator"
$password="FakePassword"

Write-Host -Object "Connecting $context... -> $name "  -BackgroundColor Yellow -ForegroundColor Blue

try
{
        $DC = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext($context,$name,$username,$password)
        Write-Host -Object "Successfully connected to $context using discovery account $username." -BackgroundColor Green -ForegroundColor Blue
        Write-Host -Object "Retrieving details of the forest..." -BackgroundColor Yellow -ForegroundColor Blue

        $Forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetForest($DC)        
        $Forest.Name
        Write-Host -Object "Successfully retrived your forest..." -BackgroundColor Green -ForegroundColor Blue

}

catch [System.DirectoryServices.ActiveDirectory.ActiveDirectoryObjectNotFoundException]
{
    Write-Host "ActiveDirectoryObjectNotFoundException exception"

}

catch [System.Security.Authentication.AuthenticationException]
{
    Write-Host "AuthenticationException exception ( Catch Block )"

}

finally
{
    Write-Host "cleaning up ...( Finally Block )"
}

输出

Connecting forest... -> Web.Metacash.Com 
Successfully connected to forest using discovery account fake\Administrator.
Retrieving details of the forest...
AuthenticationException exception ( Catch Block )
cleaning up ...( Finally Block )

如何获取原始失败的消息而不是给出我自己的消息,比如使用$ _。消息或什么?

1 个答案:

答案 0 :(得分:0)

$ _应该在catch块中有一个ErrorRecord。例外应该在那里。例如,使用$_.Exception.Message来获取其消息。当然,错误记录有关于错误的更多信息。 $_.InvocationInfo.ScriptLineNumber将包含发生错误的行号。