Windows PowerShell提供了两种报告错误的机制:一种机制用于终止错误(System.Management.Automation.Cmdlet.Throwterminatingerror方法),另一种机制用于非终止错误(System.Management.Automation.Cmdlet.WriteError 方法)。错误是由Cmdlet(具体的命令)判断、发现并报告的,报告的方法就是调用自身(System.Management.Automation....
通过ThrowTerminatingError 触发的错误称为 Terminating Errors。本质上它是创建了一个异常,所以我们可以使用 catch 语句来捕获 Terminating Errors。因此 Terminating Errors 的另外一个名字叫 Exceptions。默认情况下,Terminating Errors 不影响后面命令的执行! 把下面的代码保存到文件 exception.ps1 中: #下面的命令不存在...
Windows PowerShell 提供兩種報告錯誤的機制:終止錯誤的機制,另一個機制用於 非終止錯誤。 請務必讓 Cmdlet 正確報告錯誤,讓執行 Cmdlet 的主應用程式可以適當地回應。 當發生錯誤時,您的 Cmdlet 應該呼叫 System.Management.Automation.Cmdlet.ThrowTerminatingError* 方法,而錯誤不會或不應該允許 Cmdlet 繼續處理其...
try { throw "exception test!" } catch { Write-Warning $_ } if (2 -ne 1){ throw "Terminating Error!" } 1. 2. 3. 参考: 在 Windows PowerShell 中使用 –ErrorAction (–EA) 捕获错误 Chapter 11. Error Handling PowerShell 在线教程...
由于$PSItem 是ErrorRecord,因此还可以使用 ThrowTerminatingError 以这种方式重新引发。PowerShell 复制 catch { $PSCmdlet.ThrowTerminatingError($PSItem) } 这会将错误源更改为 Cmdlet,并向 Cmdlet 用户隐藏函数内部信息。Try 可能会创建终止错误Kirk Munro 指出,某些异常仅在 try/catch 块内执行时为终止错误。
當發生錯誤時,函式可以呼叫兩個不同的方法。 當發生非終止錯誤時,函式應該呼叫WriteError方法,如方法一節中所述Write。 當終止錯誤發生且函式無法繼續時,應該呼叫ThrowTerminatingError方法。 您也可以使用Throw語句來終止錯誤,以及針對非終止錯誤使用 Write-ErrorCmdlet。
Terminating Errors 通过ThrowTerminatingError 触发的错误称为 Terminating Errors。本质上它是创建了一个异常,所以我们可以使用 catch 语句来捕获 Terminating Errors。因此 Terminating Errors 的另外一个名字叫 Exceptions。默认情况下,Terminating Errors 不影响后面命令的执行!
这就是输出的循环。另外我们还有一种终止方式,就是使用 ThrowTerminatingError() 的方法。我们知道 PowerShell 里面其实有很多 Exception 被抛出之后是不会终止的。我们需要规定它的 OnErrorAction 才可以正常终止他。而这里的 TerminatingError 就是会造成强制终止的错误。
終止錯誤是藉由擲回例外狀況或ThrowTerminatingError方法來回報。 請注意,Cmdlet 也會攔截並重新擲回例外狀況(例如OutOfMemory),但它們不需要重新擲回例外狀況,因為 PowerShell 執行時間也會攔截例外狀況。 您也可以針對您的情況特定的問題定義自己的例外狀況,或使用其錯誤記錄將其他資訊新增至現有的例外狀況。
The method takes as an argument an instance of an ErrorRecord, which allows you to include more than just the exception (the cause of the error).You really shouldn't throw an exception in a cmdlet. Instead, ThrowTerminatingError allows you to stop the execution of the pipeline and provide...