Write-Error "$($_.exception.message)" # Path not allowed. } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 注意 通常,不要使用Throw进行参数验证。 改为使用验证属性。 如果无法将代码与这些属性一起使用,则可以使用Throw。
我指出这一点,是因为Write-Error和其他非终止错误不会触发catch。 忽略异常 在这种情况下,捕获错误只是为了抑制它。 这样做时要谨慎,因为它会使故障排除变得非常困难。 基本命令语法 下面简要概述了 PowerShell 中使用的基本异常处理语法。 Throw 若要创建自己的异常事件,请使用throw关键字引发异常。
若要宣告終止錯誤,請使用Throw關鍵詞。 如需詳細資訊,請參閱about_Throw。 範例 範例1:撰寫 RegistryKey 物件的錯誤 PowerShell Get-ChildItem|ForEach-Object{if($_.GetType().ToString()-eq"Microsoft.Win32.RegistryKey") {Write-Error"Invalid object"-ErrorIdB1-TargetObject$_}else{$_} } ...
若要声明终止错误,请使用 Throw 关键字。有关详细信息,请参阅 about_Throw。示例示例1:编写 RegistryKey 对象的错误PowerShell 复制 Get-ChildItem | ForEach-Object { if ($_.GetType().ToString() -eq "Microsoft.Win32.RegistryKey") { Write-Error "Invalid object" -ErrorId B1 -TargetObject $_ }...
This class implements the Write-Error command. C++Copy publicrefclassWriteOrThrowErrorCommand:System::Management::Automation::PSCmdlet Inheritance Object InternalCommand Cmdlet PSCmdlet WriteOrThrowErrorCommand Derived Microsoft.PowerShell.Commands.WriteErrorCommand ...
WriteOrThrowErrorCommand Constructor Reference Feedback Definition Namespace: Microsoft.PowerShell.Commands Assembly: Microsoft.PowerShell.Commands.Utility.dll Package: Microsoft.PowerShell.Commands.Utility v7.4.0 C++ 复制 public: WriteOrThrowErrorCommand(); Applies to 产品版本 PowerShell SDK 7.2....
PowerShell 异常处理(trap / try…catch / Throw / $Error / $ConfirmPreference),当处理一些特殊命令的时候,系统会进行提示。或者语句有错误时,则终止命令
在catch 块中,可以使用 $_(也称为 $PSItem)访问当前错误。 对象的类型为 ErrorRecord。PowerShell 复制 try { NonsenseString } catch { Write-Host "An error occurred:" Write-Host $_ } 运行此脚本会产生以下结果:Output 复制 An Error occurred: The term 'NonsenseString' is not recognized as ...
在catch块中,可以使用$_(也称为$PSItem)访问当前错误。 对象的类型为ErrorRecord。 PowerShell复制 try{ NonsenseString } catch {Write-Host"An error occurred:"Write-Host$_} 运行此脚本会产生以下结果: Output An Error occurred: The term 'NonsenseString' is not recognized as the name of a cmdlet,...
From https://twitter.com/rjmholt/status/1263258755849846784. I wasn't able to find an existing issue, closed or open, so I've opened this one. Example: function Throw-Break { break } try { Write-Host "main" Throw-Break Write-Host "thrown...