I have Powershell script which I use to remove MFA authentication methods of a user through MS-Graph.
At a certain point the code executes this command:
try  {
    Remove-MgUserAuthenticationPhoneMethod -UserId $userId -PhoneAuthenticationMethodId $methodId
    Write-Output "phoneAuthenticationMethod removed successfully"
} catch {
    Write-Output "Error removing phoneAuthenticationMethod: $_"    
}     
for reasons that I won't explain here I want the code to not write to SDT-ERR in case of an exception but only to STD-OUT
However when I run the script and it fails because it finds that the PhoneMethod is the default method and therefore cannot be removed, the error message is still written to STD-ERR.
Remove-MgUserAuthenticationPhoneMethod : The requested authentication method id of 
[3179e48a-750b-4051-897c-87b9720928f7] matches the user's current default authentication method, and cannot be deleted 
until the default authentication method is changed
Status: 400 (BadRequest)
ErrorCode: badRequest
Date: 2024-08-21T13:59:08
Headers:
Transfer-Encoding             : chunked
Vary                          : Accept-Encoding
Strict-Transport-Security     : max-age=31536000
request-id                    : 4c164369-1871-4d05-b984-3e4a57f3a789
client-request-id             : fd5c10d1-a4aa-4c43-a577-ffd708f5f866
x-ms-ags-diagnostic           : {"ServerInfo":{"DataCenter":"North 
Europe","Slice":"E","Ring":"4","ScaleUnit":"004","RoleInstance":"DB1PEPF00061555"}}
Date                          : Wed, 21 Aug 2024 13:59:08 GMT
At D:\Powershell\ClearMFAMethodsOnAzure.ps1:65 char:21
+ ...             Remove-MgUserAuthenticationPhoneMethod -UserId $userId -P ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: ({ UserId = 4d37... , Headers =  }:<>f__AnonymousType168`4) [Remove-Mg 
   UserAu...neMethod_Delete], Exception
    + FullyQualifiedErrorId : badRequest,Microsoft.Graph.PowerShell.Cmdlets.RemoveMgUserAuthenticationPhoneMethod_Dele 
   te
I would have expected that the exception would be caught by the catch and therefore the message "Error removing phoneAuthenticationMethod: $_" would be written to STD-OUT
However in the logs I find instead the message of: Write-Output "phoneAuthenticationMethod removed successfully"
and the stack trace mentioned above in STD-ERR and I don't understand why, it seems to me a really anomalous behavior.
What could be the cause?
Thanks in advance.
-ErrorAction Stopor set$ErrorActionPreference = 'Stop'.ThrowTerminatingErrorthey there is no need to set the preference toStopand if the cmdlet is usingWriteErrorthen it depends on your error preference which by default is set toContinue(this is what is happening to you in this case).