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"))}





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.