about_Throw

简短说明

介绍了生成终止错误的 throw 关键字。

长说明

throw 关键字会导致终止错误。 可以使用 throw 关键字停止对命令、函数或脚本的处理。

例如,可以在 throw 语句的脚本块中使用 if 关键字来响应条件,或者将其用在 catchtry-catch- 语句的 finally 块中。

throw 关键字可以引发任何对象,例如用户消息字符串或导致了错误的对象。

语法

throw 关键字的语法如下:

throw [<expression>]

throw 语法中的表达式是可选的。 如果 throw 语句未出现在 catch 块中,并且未包含表达式,则它会生成 ScriptHalted 错误。

throw
ScriptHalted
At line:1 char:6
+ throw <<<<
+ CategoryInfo          : OperationStopped: (:) [], RuntimeException
+ FullyQualifiedErrorId : ScriptHalted

如果在没有表达式的 throw 块中使用 catch 关键字,它将再次引发当前 RuntimeException。 有关详细信息,请参阅 about_Try_Catch_Finally

引发字符串

throw 语句中的可选表达式可以是字符串,如以下示例所示:

throw "This is an error."
This is an error.
At line:1 char:6
+ throw <<<<  "This is an error."
+ CategoryInfo          : OperationStopped: (This is an error.:String) [], R
untimeException
+ FullyQualifiedErrorId : This is an error.

引发其他对象

表达式还可以是一个对象,该对象引发表示 PowerShell 进程的对象,如以下示例所示:

throw (Get-Process pwsh)
At line:1 char:6
+ throw <<<<  (Get-Process powershell)
+ CategoryInfo          : OperationStopped: (System.Diagnostics.Process (Pow
erShell):Process) [],
RuntimeException
+ FullyQualifiedErrorId : System.Diagnostics.Process (PowerShell)

可以使用 自动变量中 ErrorRecord 对象的 TargetObject 属性来查看错误。$Error

$Error[0].TargetObject
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
319      26    61016      70864   568     3.28   5548 PowerShell

你还可以 throw ErrorRecord 对象或 .NET 异常。 以下示例使用 throw 关键字引发 System.FormatException 对象。

$formatError = New-Object System.FormatException
throw $formatError
One of the identified items was in an invalid format.
At line:1 char:6
+ throw <<<<  $formatError
+ CategoryInfo          : OperationStopped: (:) [], FormatException
+ FullyQualifiedErrorId : One of the identified items was in an invalid
format.

生成的错误

throw 关键字可以生成 ErrorRecord 对象。 ErrorRecord 对象的 Exception 属性包含 RuntimeException 对象。 ErrorRecord 对象和 RuntimeException 对象的其余部分因被引发的对象而异。

throw 对象包装在 ErrorRecord 对象中,ErrorRecord 对象自动保存在 自动变量中。$Error

使用 throw 创建强制参数

与以前版本的 PowerShell 不同,请勿使用 throw 关键字进行参数验证。 有关正确方式,请参阅 about_Functions_Advanced_Parameters

另请参阅