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.
1..2 | ForEach-Object {Write-Error -Message "Error number $_"}
1..2 | ForEach-Object {Write-Error -Message "Error number $_" -Exception ([System.Exception]::new("Generic Exception"))}
[System.ConsoleColor]::Black
background:
$ErrorView
) and line breaks are stripped out by design (See github issue #24108)-Exception
parameter is used or not, even when $ErrorView = 'NormalView'
.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.