Skip to main content

Powershell : How to export only errors from powershell command?

Sometimes, you need to export only the errors to your file, for example to show what needs to be corrected.

As you know, you can do an export from powershell cmd-let to a xml, csv or txt.
For example:
Get-Mailbox |Export-Csv .\mailboxes
Get-Mailbox |Export-Clixml
Get-Mailbox > mailboxes.txt

Additionally,  working in the loop, you can append data to the file, using -Append switch:
$users|%{Get-Mailbox $_.id|Export-Csv .\mailboxes -Append}
But what to do in the situations when you need to export only errors in the current command?
For example you've created mailboxes according to the list, but then some of them were deleted.
One of the possibilities is to compare your list with errors from cmd-let.
You can do it manually, but it could be painful.
I propose you to use pipeline with using not well known switch >>.
This will output only errors to your txt file.
$users|%{get-mailbox $_.userprincipalname |select displayname, userprincipalname} 2>>MailboxNotExists.txt
Here are the switches you can use:
 > - Redirect pipeline output to a file,overwriting the current contents.
 >> - Redirect pipeline output to a file,appending to the existing content.
2>> - Redirect error output to a file,appending to the current contents.
2> - Redirect error output to a file,overwriting the current contents.
2>&1 - The error messages are written to the output pipe instead of theerror pipe.

Good reference here:
https://devcentral.f5.com/articles/powershell-abcs-o-is-for-output