如何设置powershell脚本以仅显示简短的错误描述

wel*_*tty 4 powershell

有没有办法在运行脚本时显示错误描述时只获取错误消息?

我有一个运行的脚本,当发生错误时,我会在不同的时间收到错误消息,例如,如果我没有将参数传递给我写的函数,我会得到:

    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)
Run Code Online (Sandbox Code Playgroud)

这很好,但我想要的是能够设置一个首选项(如ErrorAction),它只会显示错误信息,而不是所有额外的goo都很好,但是我的控制台却很混乱.所以不是上面的,我只想看到第一行:

No Setup Location specified (i.e. \\server\share\folder)
Run Code Online (Sandbox Code Playgroud)

mjo*_*nor 5

您可以设置$ErrorView'CategoryView'获得更简洁的错误报告:

$ErrorView = 'CategoryView'
Get-Item foo

ObjectNotFound: (C:\foo:String) [Get-Item], ItemNotFoundException
Run Code Online (Sandbox Code Playgroud)

默认值为'NormalView',提供更详细的输出:

$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
Run Code Online (Sandbox Code Playgroud)

  • 太棒了. (2认同)