PowerShell stores errors that it encounters in a circular error buffer variable named $Error. $Error also contains a count property to count the number of errors in the buffer. To figure out how many errors we could hold was pretty straight forward. All I had to do was create a script that generated an error and see how high $error.count got. At this point I didn’t even know if there was a maximum or not.
$ErrorCount = 0
do {
$LastErrorCount = $ErrorCount
Get-ChildItem "c:\bogusfile.txt" -ErrorAction SilentlyContinue
$ErrorCount = $Error.Count
} while ($LastErrorCount -ne $ErrorCount)
"There are $ErrorCount errors in the error buffer."
Low and behold there is a maximum number of errors that the error buffer can hold. That number is 256, which just so happens to be the default.
After finding a maximum of 256, I also wondered if that was something I had control over. So I dug a little deeper, and sure enough there is a way to control the maximum size of the error buffer. There is a $MaximumErrorCount variable made exactly for that purpose (nice, the name even makes sense). Just as a quick test I set $MaximumErrorCount to 512, and reran my test.
$MaximumErrorCount = 512
$ErrorCount = 0
do {
$LastErrorCount = $ErrorCount
Get-ChildItem "c:\bogusfile.txt" -ErrorAction SilentlyContinue
$ErrorCount = $Error.Count
} while ($LastErrorCount -ne $ErrorCount)
''
"There are $ErrorCount errors in the error buffer."
Sure enough, I now had 512 errors in my error buffer.
I had never really thought about this before and I’m not sure I’d ever need to handle more than the default number of 256 errors, but this is another nice to know fact. I’ve been working with PowerShell for quite some time and this is just another example that there’s always something left to learn.
Happy scripting, everyone!
See also
- SQL Saturday 723, March 24, 2018 in Rochester, NY. Join us and kick your SQL Server knowledge up a notch!
- SQL Saturday 622. Join me July 29, 2017 in Albany, NY and learn to Paint with PowerShell!
- SQL Saturday 619. Join me April 29, 2017 in Rochester, NY and learn to Paint with PowerShell!
- Convert User Friendly Retention to DateTime value with PowerShell
- Speaking at SQL Saturday 513 in Albany, NY on July 30th - PowerShell and SQL Server