Capturing powershell warning


I am trying to capture the warning that gets thrown if I try to remove mailbox permissions from a mailbox for someone who doesn’t have permissions in the first place.

There is no output in either output2.txt or warning.txt – what am I doing wrong?

The warnings I am trying to capture appear in yellow and say:

Thanks for all the help so far! My code now looks like this:



Given the question’s generic title, let me first recap how capturing warnings works in general:

  • In a file such as warnings.txt: with 3> warnings.txt
    • To suppress warnings ad hoc: 3> $null
  • In a variable such as $warnings: with -WarningVariable warnings (-wv warnings)
    • However, that still passes the warnings through and therefore prints them, so in order to prevent that you must also use 3> $null or -WarningAction SilentlyContinue.

Note that these constructs must be applied to the very command producing the warnings, as (by default) only the success output stream (the stream with index 1) is sent through the pipeline:

As for what you tried:

There is no output in either output2.txt or warning.txt

  • Presumably, there is no output in output2.txt, because the Remove-MailboxPermission has not produced any success output yet at the time it throws an exception. When the exception occurs, control is instantly transferred to catch handler, so the pipeline is stopped right there, and Out-File never receives input from Remove-MailboxPermission‘s success stream.
    • Note that try / catch only takes effect if Remove-MailboxPermission produces a statement-terminating error by default; to also make it take effect for non-terminating errors, add -ErrorAction Stop.
      If the Remove-MailboxPermission produces just warnings – and no error at all – then try / catch won’t have any effect.
  • There is no output in warning.txt (even with the line re-activated by removing the initial #), because try / catch only catches error output, not warnings; that is, the warnings have already printed by the time the catch handler is processed.


Capturing powershell warning by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply