Search code examples
powershellwrite-error

Line break between consecutive error records missing when using Write-Error's -Exception parameter


Why do Windows PowerShell 5.1 and ISE display a line break between consecutive error records produced by Write-Error, but do not display a line break if the -Exception parameter is used? So far I haven't found anything online mentioning this difference in output.




Output Comparison:


Error Test (Without Exception).ps1
1..2 | ForEach-Object {Write-Error -Message "Error number $_"}

Error Test (With Exception).ps1
1..2 | ForEach-Object {Write-Error -Message "Error number $_" -Exception ([System.Exception]::new("Generic Exception"))}
  • Difficult to see, but the green arrows point to the line breaks which have a [System.ConsoleColor]::Black background: Write-Error output comparison


  • Pwsh notes:
    • Pwsh made changes to how error messages are output (e.g. $ErrorView) and line breaks are stripped out by design (See github issue #24108)
    • pwsh strips out the line breaks regardless if the -Exception parameter is used or not, even when $ErrorView = 'NormalView'.



Is this a bug in Windows PowerShell 5.1?


Solution

  • While the discrepancy is surprising (and no longer affects PowerShell (Core) 7), it is important to note that the specifics of for-display formatting are not part of PowerShell's breaking-changes contract.

    That is, you should never rely on parsing such for-display-only representations and instead use OO techniques to examine errors that have occurred, such as by examining the automatic $Error variable or the content of a variable designated to receive cmdlet-specific errors via the common -ErrorVariable parameter, both of which store [System.Management.Automation.ErrorRecord] instances.

    In PowerShell 7, you can use the Get-Error cmdlet for easier visual inspection of errors.