在PowerShell中进行错误处理的正确方法是什么? [英] What is the right way to do error handling in PowerShell?

查看:255
本文介绍了在PowerShell中进行错误处理的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PowerShell是.bat和.NET的一个奇怪的组合。在.bat中,您可以从命令中检查错误级别和stderr输出。在.NET中,您会捕获异常。



cmdlet如何返回错误?他们失败时会抛出异常,还是设置$?代替?这是可配置的吗?



我还假设在PowerShell中调用的.NET函数将始终抛出异常,并且不会被shell自动捕获并转换为错误。这是正确的吗?



也许我真的应该问的是:什么是一个很好的文章,所有这一切?似乎像我这样的很多工程师,在我的cmd的.bat和.NET都有经验,我们都想知道我们应该如何在这个勇敢的新世界中做事情。

解决方案

对于单个cmdlet,有一个名为-erroraction的参数。可能的值为SilentlyContinue,Stop,Continue或Inquire。您还可以为任何这些选项指定一个名为$ errorpreference的全局变量。



在V1中,您可以使用陷阱关键字。有一个相当不错,简洁的文章描述了在V2中添加的陷阱与try / catch / finally语法之间的关键区别。



以下是使用陷阱语句的简单示例,第一个是异常类型,第二个是通用捕获所有错误陷阱

 陷阱{其他终止错误被捕获 } 
trap [System.Management.Automation.CommandNotFoundException]
{命令错误被困}
1 / $ null


PowerShell is a weird mix of .bat and .NET. In .bat, you check errorlevel and stderr output from commands. In .NET, you catch exceptions.

How do cmdlets return errors? Do they throw exceptions when they fail or do they set $? instead? Is this configurable?

I also assume that .NET functions I call in PowerShell will always throw exceptions and not get automatically caught by the shell and converted into errors. Is that correct?

Maybe what I really ought to ask is: what's a good article that goes over all of this? Seems like a lot of engineers out there like me who have experience in cmd's .bat and .NET both are wondering exactly how we ought to be doing things in this brave new world of Posh.

解决方案

For individual cmdlets, there is a parameter called -erroraction. The possible values are SilentlyContinue, Stop, Continue, or Inquire. You can also specify a global variable called $errorpreference to any of these options.

In V1, you can use the trap key word. There is a pretty good, concise article that describes the key differences between traps and try/catch/finally syntax that was added in V2.

Here is a quick example of using trap statements, the first is for a specif type of exception and the second is a generic catch all error trap

trap {"Other terminating error trapped" }
trap [System.Management.Automation.CommandNotFoundException] 
      {"Command error trapped"}
1/$null

这篇关于在PowerShell中进行错误处理的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆