我正在尝试处理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块,则会收到未处理的异常错误:凭据无效。检查用户名和密码,然后重试。但是,使用“尝试/捕获”块时,结果或错误集合都不包含任何内容。
如何正确捕获此错误,以便向用户显示“无效的用户名或密码”?
最佳答案
您正在寻找的是:
$_.Exception.Message
此变量保存最新的异常错误。
因此,在纯PowerShell中,我执行以下错误处理:
try
{
#Some cmdlet likely to throw exception
}
catch [system.exception]
{
Write-host "Exception String:"+$($_.Exception.Message)"
#do some error handling
}
问候
弓箭手
关于vb.net - 如何在PowerShell中捕获未处理的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9052634/