如何在PowerShell中捕获未处理的错误

时间:2012-01-29 10:57:15

标签: vb.net powershell exception-handling error-handling

我正在尝试处理因Microsoft Online PowerShell cmdlet使用错误的用户名和密码而导致的异常错误(来自ASP.NET网站内部)。这是一段代码:

PowerShell.Runspace = myRunSpace

Dim connect As New Command("Get-MSOnlineUser")
connect.Parameters.Add("Enabled")

Dim secureString As New System.Security.SecureString()
Dim myPassword As String = "Password"

For Each c As Char In myPassword
        secureString.AppendChar(c)
Next

connect.Parameters.Add("Credential", New PSCredential("admin@username.apac.microsoftonline.com", secureString))
PowerShell.Commands.AddCommand(connect)

Dim results As Collection(Of PSObject) = Nothing
Dim errors As Collection(Of ErrorRecord) = Nothing

results = PowerShell.Invoke()

Try
        results = PowerShell.Invoke()
Catch ex As Exception

End Try

errors = PowerShell.Streams.[Error].ReadAll()

如果我删除了Try / Catch块,则会收到Unhandled Exception错误:Credentials无效。检查用户名和密码,然后重试。但是,使用Try / Catch块时,结果或错误集合都不包含任何内容。

如何正确捕获此错误,以便向用户显示“无效的用户名或密码”?

1 个答案:

答案 0 :(得分:4)

您正在寻找的是:

$_.Exception.Message

此变量保存最新的异常错误。 所以在纯PowerShell中,我执行错误处理,如:

try
{
   #Some cmdlet likely to throw exception
}
catch [system.exception]
{
   Write-host "Exception String:"+$($_.Exception.Message)"
   #do some error handling
} 

问候 Arcass