简体   繁体   中英

How can I set a powershell script to only show short error descriptions

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)

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

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;
}

将代码包含在try / catch块中,并在catch块中打印包含在$ error变量中的第一行,其中包含$error.Exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM