I’m trying to handle an exception error caused when the wrong user name and password is used with the Microsoft Online PowerShell cmdlets (from within in an ASP.NET website). Here’s a snipped of the code:
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()
If I remove the Try/Catch block, I get an Unhandled Exception error: Credentials are not valid. Check the user name and password and try again. However, with the Try/Catch block, neither the results or errors collections contain anything.
How do I trap this error properly so I can present the user with “Invalid Username or Password”?
What you are looking for is:
This variable holds the latest exception error.
So in pure PowerShell I do my error handling like:
regards
Arcass