Powershell里面一般处理异常分为中断类型和不可中断类型。前者一般是通过try..catch..finally处理,后者一般通过ErrorAction, ErrorVariable处理。
通过try..catch处理的时候有一个问题就是catch后面跟的异常,他的名字到底怎么获取的?
比如说我执行,他会报错,因为 nnnnn这个命令不存在。
PS C:\> a=nnnnn a=nnnnn : The term ‘a=nnnnn‘ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + a=nnnnn + ~~~~~~~ + CategoryInfo : ObjectNotFound: (a=nnnnn:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
如果我想使用try ..catch捕获这个异常,如何知道这个异常的具体名字是什么?
可以通过$error这个变量来获取,最新的报错就是 $error[0], 通过他可以知道具体的Exception是什么,这样就可以有的放矢了。
PS C:\> $Error[0] | fl * -f PSMessageDetails : Exception : System.Management.Automation.CommandNotFoundException: The term ‘a=nnnnn‘ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. at System.Management.Automation.CommandDiscovery.LookupCommandInfo(String commandName, CommandTypes commandTypes, SearchResolutionOptions searchResolutionOptions, CommandOrigin commandOrigin, ExecutionContext context) at System.Management.Automation.CommandDiscovery.LookupCommandProcessor(String commandName, CommandOrigin commandOrigin, Nullable`1 useLocalScope) at System.Management.Automation.ExecutionContext.CreateCommand(String command, Boolean dotSource) at System.Management.Automation.PipelineOps.AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, ExecutionContext context) at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext) at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame) TargetObject : a=nnnnn CategoryInfo : ObjectNotFound: (a=nnnnn:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo ScriptStackTrace : at <ScriptBlock>, <No file>: line 1 PipelineIterationInfo : {}
比如这样就行了
PS C:\> try{ a=nnnnn }catch [System.Management.Automation.CommandNotFoundException]{ "error1" } error1
时间: 2024-10-27 08:08:29