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

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

    The best way in my opinion to trap errors in PowerShell would be to use the following:

    $Error[0].Exception.GetType().FullName
    

    Here is an example of how to use this properly. Basically test what you are trying to do in PowerShell with different scenarios in which your script will fail.

    Here is a typical PowerShell error message:

    PS C:\> Stop-Process -Name 'FakeProcess'
    Stop-Process : Cannot find a process with the name "FakeProcess". Verify the process name and call the cmdlet again.
    At line:1 char:1
    + Stop-Process -Name 'FakeProcess'
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (FakeProcess:String) [Stop-Process], ProcessCommandException
        + FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.StopProcessCommand
    

    Next you would get the exception of the error message:

    PS C:\> $Error[0].Exception.GetType().FullName
    Microsoft.PowerShell.Commands.ProcessCommandException
    

    You would setup your code to catch the error message as follows:

    Try
    {
        #-ErrorAction Stop is needed to go to catch statement on error
        Get-Process -Name 'FakeProcess' -ErrorAction Stop
    }
    Catch [Microsoft.PowerShell.Commands.ProcessCommandException]
    {
        Write-Host "ERROR: Process Does Not Exist. Please Check Process Name"
    }
    

    Output would look like the following instead of the Powershell standard error in above example:

    ERROR: Process Does Not Exist. Please Check Process Name
    

    Lastly, you can also use multiple catch blocks to handle multiple errors in your code. You can also include a "blanket" catch block to catch all errors you haven't handled. Example:

    Try
    {
        Get-Process -Name 'FakeProcess' -ErrorAction Stop
    }
    
    Catch [Microsoft.PowerShell.Commands.ProcessCommandException]
    {
        Write-Host "ERROR: Process Does Not Exist. Please Check Process Name"
    }
    
    Catch [System.Exception]
    {
        Write-Host "ERROR: Some Error Message Here!"
    }
    
    Catch
    {
        Write-Host "ERROR: I am a blanket catch to handle all unspecified errors you aren't handling yet!"
    }
    

提交回复
热议问题