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

后端 未结 5 1960
星月不相逢
星月不相逢 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:05

    Based on suneg's answer I wrote the following functions to allow you to effortlessly swap Write-Error with a custom function and back. I also added a check if user is invoking write-error from PowerShell ISE

    # Override the built-in cmdlet with a custom version
    function New-ErrorFunc {
            function Dyn($message){
                param($message,$ErrorAction)
                if($psISE){
                    $Host.UI.WriteErrorLine($message)
                }
                else{
                [Console]::ForegroundColor = 'red'
                [Console]::Error.WriteLine($message)
                [Console]::ResetColor()
                }
               if($ErrorAction -eq 'Stop'){
               Break
               }
            }
    
        return ${function:Dyn}
    }
    function Set-ErrorFunc(){
        param([bool]$custom=$true)
        if($custom){
        $dynfex= New-ErrorFunc
        Invoke-Expression -Command "function script:Write-Error{ $dynfex }"
        }
        else {
            $custom= Get-Command Write-Error | Where-Object {$_.CommandType -eq 'Function'} 
            if($custom){ Remove-Item function:Write-Error }
       }
    }
    
    #User our Custom Error Function
    Set-ErrorFunc 
    # Pretty-print "Something is wrong" on stderr (in red).
    Write-Error "Something is wrong"
    
    # Setting things back to normal 
    Set-ErrorFunc -custom $false
    # Print the standard bloated Powershell errors
    Write-Error "Back to normal errors"
    

提交回复
热议问题