powershell中所有错误和异常处理的方法 判断上一个程序是否运行成功(lastexitcode try catch trap)

01.$LASTEXITCODE$?

类似于linux的shell脚本,powershell也可以用记录程序退出码的方式判断命令是否执行成功

其中

  1. $?表示最后一个操作的执行状态。如果最后一个操作成功,则包含 TRUE,失败则包含 FALSE。

  2. $LASTEXITCODE则是返回上一次执行的退出码,因为linux程序通常用退出码0表示执行成功,所以我们判断$LASTEXITCODE是否为0就能判断上次程序执行是否成功。

总的来说$LASTEXITCODE,逻辑上还要多绕一圈,所以平时方便起见用$?就是了。

02.trap

trap关键词可以指定让程序终结的错误发生时,执行一系列语句。

  • trap的默认行为是在执行完statement block里的语句 后显示错误,然后会继续执行脚本或者函数
  • 在trap中使用break可以实现显示错误,然后退出执行
  • 如果想要不显示错误继续执行,可以用continue

语法

trap [[<error type>]] {<statement list>}

statement list就是终结错误发生时,会执行的语句。

错误类型定义了trap的处理范围

trap处理所有终结错误

没有类型定义的trap会在所有错误发生的时候执行。

当一个让程序终结的错误没有找到其他处理的脚本或命令,就会执行trap里面的语句,

下面是一个例子

trap {"Error found."}
function TrapTest {
    trap {"Error found."}
    nonsenseString
}

TrapTest

会出现下面的错误

Error found.
nonsenseString:
Line |
   3 |      nonsenseString
     |      ~~~~~~~~~~~~~~
     | The term 'nonsenseString' 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.

trap 中使用$_,也就是powershell自动生成的当前对象,就会被替换成输出的错误

function TrapTest {
    trap {"Error found: $_"}
    nonsenseString
}

TrapTest


Error found: The term 'nonsenseString' 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.
nonsenseString:
Line |
   3 |      nonsenseString
     |      ~~~~~~~~~~~~~~
     | The term 'nonsenseString' 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.

注意: trap可以在一个作用域代码块(scope)的任何地方定义,即使定义在一个代码块的底部,也会捕获整个代码块的错误

trap处理特定的错误

下面是只处理没有找到命令的错误的trap,trap的使用的是.net的异常类型

trap [System.Management.Automation.CommandNotFoundException]
    {"Command error trapped"}

下面是系统异常类型,System.Management.Automation.CommandNotFoundException是继承自System.Exception的

trap [System.Exception] {"An error trapped"}

当多个trap同时存在的时候powershell会匹配最精确特定的trap,如下

trap {"Other terminating error trapped" }
trap [System.Management.Automation.CommandNotFoundException] {
  "Command error trapped"
}
nonsenseString

Command error trapped
nonsenseString:
Line |
   5 |  nonsenseString
     |  ~~~~~~~~~~~~~~
     | The term 'nonsenseString' 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.

trap捕获错误的作用域

trap捕获错误以后,会执行trap内部的语句,但是错误处后续的代码还会继续执行

下面是在函数内部发生了错误的情况,错误被内部的trap捕获,并且函数的返回语句被正常执行

function function1 {
    trap { "An error: " }
    NonsenseString
    "function1 was completed"
}

function1

An error:
NonsenseString:
Line |
   3 |      NonsenseString
     |      ~~~~~~~~~~~~~~
     | The term 'NonsenseString' 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.
function1 was completed

下面的例子trap语句被放到函数外面,能够捕获到函数内部的错误,但是函数的返回语句没有被执行

function function2 {
    NonsenseString
    "function2 was completed"
}

trap { "An error: " }

function2

An error:
NonsenseString:
Line |
   2 |      NonsenseString
     |      ~~~~~~~~~~~~~~
     | The term 'NonsenseString' 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.

也就是说,trap如果在函数的外部,就可以实现捕获到错误就停止函数运行的功能。

注意:多个trap定义相同类型的错误条件的时候,只有最高处定义的trap会被使用

Remove-Item -ErrorAction Stop ThisFileDoesNotExist
trap { "whoops 1"; continue }
trap { "whoops 2"; continue }

注意:trap语句的定义域取决于它编译的位置,如果它在一个函数或者脚本中,那么当函数或脚本退出时,他们内部的trap语句就会被删除

看下面的例子,函数外的错误没有被函数内的trap捕获

function function1 {
    trap { "An error: " }
    
    "function1 was completed"
}
NonsenseString

function1 was completed
NonsenseString: C:\Projects\base\test\testexit.ps1:6:1
Line |
   6 |  NonsenseString
     |  ~~~~~~~~~~~~~~
     | The term 'NonsenseString' is not recognized as a name of a cmdlet, function,
     | script file, or executable program. Check the spelling of the name, or if a
     | path was included, verify that the path is correct and try again.

使用break和continue关键字

在trap中使用break和continue可以决定终结错误发生时,继续运行还是停止

默认没有break关键字的情况下是会继续运行的,也会输出错误

function break_example {
    trap {
        "Error trapped"
        break
    }
    1/$null
    "Function completed."
}

break_example

Error trapped
ParentContainsErrorRecordException:
Line |
   6 |      1/$null
     |      ~~~~~~~
     | Attempted to divide by zero.

使用continue语句,powershell将从错误中恢复,并且不会输出错误流

function continue_example {
    trap {
        "Error trapped"
        continue
    }
    1/$null
    "Function completed."
}

continue_example

Error trapped
Function completed.

综上,trap是一种比较简单的广范围的错误处理方式,对于更细粒度的错误处理,建议使用try catch语句

03.try catch finally

try 捕获的错误,会被自动保存到$Error变量里面,powershell会寻找catch语句来处理错误。

这个语法就和c#的异常处理比较像

语法

try {<statement list>}`
catch [[<error type>][',' <error type>]*] {<statement list>}
finally {<statement list>}

捕获错误

try { NonsenseString }
catch { "An error occurred." }

An error occurred.

使用多个catch语句

try {
   $wc = new-object System.Net.WebClient
   $wc.DownloadFile("http://www.contoso.com/MyDoc.doc","c:\temp\MyDoc.doc")
}
catch [System.Net.WebException],[System.IO.IOException] {
    "Unable to download MyDoc.doc from http://www.contoso.com."
}
catch {
    "An error occurred that could not be resolved."
}

在try catch语句中使用trap

当try语句中包含trap,即使声明了catch语句,也会执行trap,如果trap的位置比try更高,并且没有catch语句,trap也会获得控制,即使父级作用域中包含匹配的catch语句。

访问错误信息 ACCESSING EXCEPTION INFORMATION

catch语句中的$_就包含了错误信息

try { NonsenseString }
catch {
  Write-Host "An error occurred:"
  Write-Host $_
}

An Error occurred:
The term 'NonsenseString' 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.

你还可以用$_打印堆栈信息

try { NonsenseString }
catch {
  Write-Host "An error occurred:"
  Write-Host $_.ScriptStackTrace
}

An Error occurred:
at <ScriptBlock>, <No file>: line 2

使用FINALLY来释放资源

不管try块是否遇到错误,finally语句都会执行。即使catch中使用exit退出脚本,或者使用ctrl+c中止脚本都会执行。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容