您好,登錄后才能下訂單哦!
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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。