Reputation: 6098
Is there a way to get only the error message when displaying error descriptions while running a script?
I have a script that runs, and when an error occurs, I get error messages at various times, for example, if I don't pass a parameter to a function I wrote, I'll get:
No Setup Location specified (i.e. \\server\share\folder)
At \\server\share\folder\script.ps1:9 char:31
+ [string] $setupHome = $(throw <<<< "No Setup Location specified (i.e. \\server\share\folder)")
+ CategoryInfo : OperationStopped: (No Setup Locati...ojects\something):String) [], RuntimeException
+ FullyQualifiedErrorId : No Setup Location specified (i.e. \\server\share\folder)
This is fine, but what I'd like is to be able to set a preference (like ErrorAction) that only will show me the error message, and not all of the extra goo that is nice to have, but clutters up my console. So instead of the above, I'd like to only see that first line:
No Setup Location specified (i.e. \\server\share\folder)
Upvotes: 5
Views: 3236
Reputation: 68243
You can set $ErrorView
to 'CategoryView'
to get less verbose error reporting:
$ErrorView = 'CategoryView'
Get-Item foo
ObjectNotFound: (C:\foo:String) [Get-Item], ItemNotFoundException
The default is 'NormalView'
, which provides more verbose output:
$ErrorView = 'NormalView'
Get-Item foo
ObjectNotFound: (C:\foo:String) [Get-Item], ItemNotFoundException
Get-Item : Cannot find path 'C:\foo' because it does not exist.
At line:8 char:1
+ Get-Item foo
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\foo:String) [Get-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
Upvotes: 5
Reputation: 4742
Enclose the code in a try/catch block, and in the catch block print the first line that is contained in the $error variable with $error.Exception
Upvotes: 2
Reputation: 9644
You can use trap
function, put it at the beginning of your script an do some action each time an exception occurs, something like that
trap {
Write-Host $Error[0].PSMessageDetails
continue;
}
Upvotes: 1