共用方式為


關於 Trap

簡短描述

描述處理終止錯誤的關鍵字。

完整描述

終止錯誤會阻止語句執行。 如果 PowerShell 無法以某種方式處理終止錯誤,PowerShell 也會停止在目前的管線中執行函式或腳本。 在其他語言(例如 C # )中,終止錯誤稱為例外狀況。

Trap關鍵字會指定發生終止錯誤時要執行的語句清單。 Trap 語句會處理終止錯誤,並允許腳本或函式繼續執行,而不是停止。

Trap 語句也可能更複雜。 Trap 的語句清單可以包含多個條件或函式呼叫。 「陷阱」可以寫入記錄、測試條件,甚至是執行另一個程式。

Syntax

Trap 語句具有下列語法:

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

當發生終止錯誤時,Trap 語句會包含要執行的語句清單。 Trap 語句是由關鍵字組成 trap ,選擇性地後面接著類型運算式,而語句區塊則包含在捕捉到錯誤時要執行的語句清單。 型別運算式會精煉 trap 所攔截的錯誤類型。

腳本或命令可以有多個 Trap 語句。 Trap 語句可以出現在腳本或命令的任何位置。

將所有終止錯誤全部設為

當發生未在腳本或命令中以另一種方式處理的終止錯誤時,PowerShell 會檢查是否有處理錯誤的 Trap 語句。 如果有 Trap 語句,PowerShell 會繼續在 Trap 語句中執行腳本或命令。

下列範例是非常簡單的 Trap 語句:

trap {"Error found."}

此 Trap 語句會攔截任何終止錯誤。

在下列範例中,函式包含會造成執行階段錯誤的未意義字串。

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

TrapTest

執行此函數會傳回下列內容:

Error found.

下列範例包含使用自動變數顯示錯誤的 Trap 語句 $_

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 then try
again.

重要

Trap 語句可以定義于指定範圍內的任何位置,但一定會套用到該範圍中的所有語句。 在執行時間,區塊中的陷阱會在執行任何其他語句之前定義。 在 JavaScript 中,這稱為hoisting。 這表示,即使執行未在其定義的時間點之前,也會套用至該區塊中的所有語句。 例如,在腳本結尾定義 trap,並在第一個語句中擲回錯誤,仍然會觸發該陷阱。

捕捉特定錯誤

腳本或命令可以有多個 Trap 語句。 可以定義陷阱來處理特定的錯誤。

下列範例是 Trap 語句,它會攔截特定的錯誤system.management.automation.commandnotfoundexception

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

當函式或腳本遇到不符合已知命令的字串時,此 Trap 語句會顯示「命令錯誤攔截」字串。 執行 Trap 語句清單之後,PowerShell 會將錯誤物件寫入錯誤資料流程,然後繼續執行腳本。

PowerShell 會使用 Microsoft .NET Framework 的例外狀況類型。 下列範例會指定Exception錯誤類型:

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

System.management.automation.commandnotfoundexception 錯誤類型繼承自 system.exception 類型。 此語句會將未知命令所建立的錯誤加以捕捉。 它也會捕捉其他錯誤類型。

腳本中可以有一個以上的 Trap 語句。 每個錯誤類型只能由一個 Trap 語句來攔截。 當發生終止錯誤時,PowerShell 會在目前的執行範圍內,搜尋具有最特定相符項的陷阱。

下列腳本範例包含錯誤。 此腳本包含一般的 Trap 語句,它會攔截任何終止錯誤和 Trap 指定system.management.automation.commandnotfoundexception類型的特定語句。

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

執行此腳本會產生下列結果:

Command error trapped
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.
At C:\temp\test\traptest.ps1:5 char:1
+ nonsenseString
+ ~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (nonsenseString:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

由於 PowerShell 無法將 "nonsenseString" 辨識為 Cmdlet 或其他專案,因此會傳回system.management.automation.commandnotfoundexception錯誤。 特定的 Trap 語句會攔截此終止錯誤。

下列腳本範例包含相同的 Trap 語句和不同的錯誤:

trap {"Other terminating error trapped" }
trap [System.Management.Automation.CommandNotFoundException]
    {"Command error trapped"}
1/$null

執行此腳本會產生下列結果:

Other terminating error trapped
Attempted to divide by zero.
At C:\temp\test\traptest.ps1:5 char:1
+ 1/$null
+ ~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException

嘗試零除時,不會建立system.management.automation.commandnotfoundexception錯誤。 相反地,其他 Trap 語句會攔截該錯誤,這會攔截任何終止錯誤。

捕捉錯誤和範圍

如果終止錯誤發生在與 Trap 語句相同的範圍中,則 PowerShell 會執行 Trap 所定義的語句清單。 在錯誤之後的語句中繼續執行。 如果 Trap 語句位於與錯誤不同的範圍內,則會在與 Trap 語句相同範圍的下一個語句中繼續執行。

例如,如果函式中發生錯誤,而且 Trap 語句是在函數中,則腳本會在下一個語句繼續進行。 下列腳本包含錯誤和 trap 語句:

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

稍後在腳本中,執行 Function1 函數會產生下列結果:

function1
An error:
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
then try again.
At C:\PS>TestScript1.ps1:3 char:19
+     NonsenseString <<<<

function1 was completed

函數中的 Trap 語句會攔截錯誤。 顯示訊息之後,PowerShell 會繼續執行函式。 請注意, Function1 已完成。

將此與下列範例(具有相同的錯誤和語句)進行比較 Trap 。 在此範例中,trap 語句會出現在函式之外:

function function2 {
    NonsenseString
    "function2 was completed"
    }

trap { "An error: " }

function2

Function2執行函數會產生下列結果:

An error:
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
then try again.
At C:\PS>TestScript2.ps1:4 char:19
+     NonsenseString <<<<

在此範例中,[function2 已完成] 命令未執行。 在這兩個範例中,終止錯誤會發生在函式內。 不過,在此範例中,Trap 語句不在函式的外部。 在執行 Trap 語句之後,PowerShell 不會回到函數。

警告

針對相同的錯誤狀況定義多個設陷時,會使用以詞法順序定義的第一個設陷(範圍中的最高)。

在下列範例中,只會執行具有 "糟糕! 似乎 1" 的 trap。

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

使用 breakcontinue 關鍵字

您可以 Break Continue 在 Trap 語句中使用和關鍵字,以判斷腳本或命令在終止錯誤之後是否繼續執行。

如果您 Break 在 Trap 語句清單中包含語句,則 PowerShell 會停止函數或腳本。 下列範例函數會 Break 在 Trap 語句中使用關鍵字:

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

break_example
Error trapped
Attempted to divide by zero.
At line:4 char:7

因為 Trap 語句包含關鍵字,所以函式不 Break 會繼續執行,且不會執行「函式已完成」行。

如果您 Continue 在 Trap 語句中包含語句,則 PowerShell 會在造成錯誤的語句之後繼續執行,就像沒有 Break 或一樣 ContinueContinue不過,使用關鍵字時,PowerShell 不會將錯誤寫入錯誤資料流程。

下列範例函數會 Continue 在語句中使用關鍵字 Trap

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

continue_example
Error trapped
Function completed.

函式會在攔截到錯誤之後繼續執行,而「函式已完成」語句則會執行。 錯誤資料流程不會寫入錯誤。

注意

Trap 語句提供了一種簡單的方式,可廣泛地確保範圍內的所有終止錯誤都會被處理。 如需更細微的錯誤處理,請使用使用 try / catch 語句定義陷阱的區塊 CatchCatch語句僅適用于相關語句內的程式碼 Try 。 如需詳細資訊,請參閱about_Try_Catch_Finally

另請參閱

about_Break

about_Continue

about_Scopes

about_Throw

about_Try_Catch_Finally