I'm working on a PowerShell script and need to capture both success and error messages from a cmdlet. I've heard that try-catch might not work for this scenario, so I'm trying to figure out the right approach. Here's what I've tried so far:
1. I executed `Remove-EntraGroupMember -GroupID $GroupID -MemberID $EntraUser.ID` and captured the error with `$Message = $Error`. I received an error saying 'The property '@odata.nextLink' cannot be found on this object. Verify that the property exists.'
2. I also attempted to check the success condition like this:
```
Remove-EntraGroupMember -GroupID $GroupID -MemberID $EntraUser.ID
if($? -eq $false){
$Message = $_.Exception.Message
} else {
$Message = $_.Exception.Message
}
```
However, I found that this didn't return anything on a successful run.
3. Lastly, I tried running `$Error = Remove-EntraGroupMember -GroupID $GroupID -MemberID $EntraUser.ID` and then retrieving the message with `$Message = $Error.Exception.Message`. Again, this didn't provide feedback for successful executions.
Any advice on how to best capture these results would be greatly appreciated!
2 Answers
Have you checked the contents of `$Error` after your last command, not just `$Error.Exception.Message`? Sometimes the complete error object provides more context and could help you understand what's going wrong.
I’ve got a snippet that works for me. You can modify it for your needs:
```powershell
try {
Get-ChildItem -Path 'C:NonExistentDirectory' -ErrorAction Stop
} catch {
$ErrorMessage = $_.Exception.Message
Write-Host "An error occurred: $ErrorMessage"
}
```
This way, you can catch specific error messages and other details, like categories. It might give you clues!

But isn’t try-catch meant to handle errors only? What if the cmdlet runs successfully?