Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 591
warpdesign Avatar asked Sep 18 '25 21:09

warpdesign


1 Answers

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).

like image 141
briantist Avatar answered Sep 23 '25 05:09

briantist