Reputation: 1032
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("[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()
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"?
Upvotes: 1
Views: 8700
Reputation: 932
What you are looking for is:
$_.Exception.Message
This variable holds the latest exception error. So in pure PowerShell I do my error handling like:
try
{
#Some cmdlet likely to throw exception
}
catch [system.exception]
{
Write-host "Exception String:"+$($_.Exception.Message)"
#do some error handling
}
regards Arcass
Upvotes: 4