您好,登錄后才能下訂單哦!
Powershell里面一般處理異常分為中斷類(lèi)型和不可中斷類(lèi)型。前者一般是通過(guò)try..catch..finally處理,后者一般通過(guò)ErrorAction, ErrorVariable處理。
通過(guò)try..catch處理的時(shí)候有一個(gè)問(wèn)題就是catch后面跟的異常,他的名字到底怎么獲取的?
比如說(shuō)我執(zhí)行,他會(huì)報(bào)錯(cuò),因?yàn)?nnnnn這個(gè)命令不存在。
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捕獲這個(gè)異常,如何知道這個(gè)異常的具體名字是什么?
可以通過(guò)$error這個(gè)變量來(lái)獲取,最新的報(bào)錯(cuò)就是 $error[0], 通過(guò)他可以知道具體的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
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。