warpdesign
warpdesign

Reputation: 747

Powershell: how to remove stack trace when command returns an error?

When a command returns an error, I get like an error message, plus what looks like a full stack of the error:

C:\> dir foo
dir : Cannot find path 'C:\foo' because it does not exist.
At line:1 char:1
+ dir foo
+ ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\foo:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Is there a way to only see the error (that's the only thing usefull for me) and not display the full stack ?

Like:

C:\> dir foo
dir : Cannot find path 'C:\foo' because it does not exist.

Upvotes: 4

Views: 1826

Answers (2)

Χpẘ
Χpẘ

Reputation: 3451

All powershell errors are captured in the auto variable $error. The item at index zero ($error[0]) is the most recent, index 1 next to most recent, etc. Each object in the array is a System.Management.Automation.ErrorRecord. An ErrorRecord contains a number of properties. You can use the select-object cmdlet to see a subset of properties:

$error[0]|select * -excludeproperty *stacktrace

If you want to be able to view the error record at an arbitrary while you're developing a script I'd suggest a function in your profile maybe like:

function show-myError {
  param( $errorIndex = 0)
  # You can also add anything else you want to exclude
  $error[0]|select * -exclude *stacktrace 
}
sal err show-myError

On the other hand if you're getting an error at a specific place in a specific script you can use catch/try as suggested in earlier answer. Or if you don't have a specific place, but do have a specific script, then I suggest trap, which you can place at the top of a function or top of a PS1 file. In the catch block or trap block you can output $error[0] using select with the -exclude parameter.

Upvotes: 0

briantist
briantist

Reputation: 47802

You need to catch the error if you want to control how or what is displayed:

try {
    dir foo -ErrorAction Stop
} catch {
    Write-Host $_
}

Sometimes you'll need to add -ErrorAction Stop (or $ErrorActionPreference = 'Stop') to ensure that all errors are terminating (so they can be caught).

Upvotes: 2

Related Questions