How can I display a 'naked' error message in PowerShell without an accompanying stacktrace?

后端 未结 5 1910
星月不相逢
星月不相逢 2021-02-05 04:25

How can I write to standard error from PowerShell, or trap errors such that:

  • An error message is displayed as an error (truly writing to standard error so that Tea
5条回答
  •  醉梦人生
    2021-02-05 05:00

    Building on the idea in a previous answer, you can override the built-in Write-Error cmdlet temporarily with a custom function.

    # Override the built-in cmdlet with a custom version
    function Write-Error($message) {
        [Console]::ForegroundColor = 'red'
        [Console]::Error.WriteLine($message)
        [Console]::ResetColor()
    }
    
    # Pretty-print "Something is wrong" on stderr (in red).
    Write-Error "Something is wrong"
    
    # Setting things back to normal 
    Remove-Item function:Write-Error
    
    # Print the standard bloated Powershell errors
    Write-Error "Back to normal errors"
    

    With this you are utilizing the fact that Powershell Functions takes precedence over cmdlets.

    https://technet.microsoft.com/en-us/library/hh848304.aspx

    This is the most elegant approach I've been able to come up with to both show beautiful and concise error messages, as well as letting TeamCity detect problems easily.

提交回复
热议问题