2012-01-29 34 views
1

我試圖處理在Microsoft Online PowerShell cmdlet(從ASP.NET網站中)使用錯誤的用戶名和密碼時導致的異常錯誤。這裏有一個剪斷代碼:如何在PowerShell中捕獲未處理的錯誤

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("[email protected]", 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塊,我得到一個未處理的異常錯誤:證書是無效的。檢查用戶名和密碼,然後重試。但是,對於Try/Catch塊,結果或錯誤集合都不包含任何內容。

如何正確捕獲此錯誤,以便向用戶顯示「無效的用戶名或密碼」?

回答

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

相關問題