Method 1: Try, Catch, Finally
Try: Try to execute a command
Catch: Catches any errors, triggers only for Terminating Errors, so you may need to set a ErrorAction -Stop (EA) for errors that are not terminating.
Finally: Runs regardless if a error occurs.
1 2 3 |
Try { Set-Mailbox -Identity -PrimarySmtpAddress -EA STOP } Catch { $_ | Out-File C:\errors.txt -Append } Finally { Echo "runs no matter what"} |
Method 2: Output error directly to error log
1 |
Set-Mailbox -PrimarySmtpAddress <primarysmtpaddress> 2>> C:\errors.txt |
Method 3: Customize a out-file to a error log
1 2 3 |
"this occurred" | out-file c:\error.log -append $x | out-file c:\error.log -append ${get-date) | out-file c:\error.log -append |