Powershell 如何获取异常的名称
Powershell里面一般处理异常分为中断类型和不可中断类型。前者一般是通过try..catch..finally处理,后者一般通过ErrorAction, ErrorVariable处理。
通过try..catch处理的时候有一个问题就是catch后面跟的异常,他的名字到底怎么获取的?
比如说我执行,他会报错,因为 nnnnn这个命令不存在。
PSC:\>a=nnnnna=nnnnn:Theterm'a=nnnnn'isnotrecognizedasthenameofacmdlet,function,scriptfile,oroperableprogram.Checkthespellingofthename,orifapathwasincluded,verifythatthepathiscorrectandtryagain.Atline:1char:1+a=nnnnn+~~~~~~~+CategoryInfo:ObjectNotFound:(a=nnnnn:String)[],CommandNotFoundException+FullyQualifiedErrorId:CommandNotFoundException
如果我想使用try ..catch捕获这个异常,如何知道这个异常的具体名字是什么?
可以通过$error这个变量来获取,最新的报错就是 $error[0], 通过他可以知道具体的Exception是什么,这样就可以有的放矢了。
PSC:\>$Error[0]|fl*-fPSMessageDetails:Exception:System.Management.Automation.CommandNotFoundException:Theterm'a=nnnnn'isnotrecognizedasthenameofacmdlet,function,scriptfile,oroperableprogram.Checkthespellingofthename,orifapathwasincluded,verifythatthepathiscorrectandtryagain.atSystem.Management.Automation.CommandDiscovery.LookupCommandInfo(StringcommandName,CommandTypescommandTypes,SearchResolutionOptionssearchResolutionOptions,CommandOrigincommandOrigin,ExecutionContextcontext)atSystem.Management.Automation.CommandDiscovery.LookupCommandProcessor(StringcommandName,CommandOrigincommandOrigin,Nullable`1useLocalScope)atSystem.Management.Automation.ExecutionContext.CreateCommand(Stringcommand,BooleandotSource)atSystem.Management.Automation.PipelineOps.AddCommand(PipelineProcessorpipe,CommandParameterInternal[]commandElements,CommandBaseAstcommandBaseAst,CommandRedirection[]redirections,ExecutionContextcontext)atSystem.Management.Automation.PipelineOps.InvokePipeline(Objectinput,BooleanignoreInput,CommandParameterInternal[][]pipeElements,CommandBaseAst[]pipeElementAsts,CommandRedirection[][]commandRedirections,FunctionContextfuncContext)atSystem.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrameframe)atSystem.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrameframe)TargetObject:a=nnnnnCategoryInfo:ObjectNotFound:(a=nnnnn:String)[],CommandNotFoundExceptionFullyQualifiedErrorId:CommandNotFoundExceptionErrorDetails:InvocationInfo:System.Management.Automation.InvocationInfoScriptStackTrace:at<ScriptBlock>,<Nofile>:line1PipelineIterationInfo:{}
比如这样就行了
PSC:\>try{a=nnnnn}catch[System.Management.Automation.CommandNotFoundException]{"error1"}error1
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。