【问题标题】:PowerShell Try Catch error handling function doesn't show my custom warning message [duplicate]PowerShell Try Catch 错误处理功能不显示我的自定义警告消息 [重复]
【发布时间】:2020-05-26 02:30:48
【问题描述】:

我正在尝试编写一个简单的 PowerShell 代码来创建一个注册表项,然后使用 TRY 和 CATCH 来处理/捕获任何可能发生的潜在异常。作为测试场景,如果我修改注册表路径,我希望得到“脚本无法创建注册表项”。不幸的是,TRY/CATCH 错误处理功能对我不起作用,除了错误本身,控制台中没有任何显示。

$NetBTpath = "HKLM:\System\CurrentControlSet\Services\NetBT\Parameters"
$RegValueName = "NodeType"

Try
{
    if (((Get-ItemProperty $NetBTpath).PSobject.Properties.Name -contains $RegValueName) -ne "True")
    {
        New-ItemProperty -Path $NetBTpath -Name "NodeType" -Value 2  -PropertyType "dword"
    }
}

Catch [System.Exception]
{
Write-warning "Script failed to create the registry key"
}

只要注册表路径正确,它就可以正常工作,但是如果我将注册表文件夹 ...\NetBT\Parameters 重命名为 ...\NetBT\Parameters1,我只会看到:

Get-ItemProperty:找不到路径“HKLM:\System\CurrentControlSet\Services\NetBT\Parameters”,因为它不存在。 在 C:\temp\NetBT_RegConfig222.ps1:10 char:11 + if (((Get-ItemProperty $NetBTpath).PSobject.Properties.Name -cont ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (HKLM:\System\Cu...etBT\Parameters:String) [Get-ItemProperty], ItemNotFoundExcep 化 + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemPropertyCommand

New-ItemProperty:找不到路径“HKLM:\System\CurrentControlSet\Services\NetBT\Parameters”,因为它不存在。 在 C:\temp\NetBT_RegConfig222.ps1:12 char:9 + New-ItemProperty -Path $NetBTpath -Name "NodeType" -Value 2 ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (HKLM:\System\Cu...etBT\Parameters:String) [New-ItemProperty], ItemNotFoundExcep 化 + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.NewItemPropertyCommand

我已经尝试过只使用Catch {}Catch [System.Management.Automation.ItemNotFoundException]

请指教。

【问题讨论】:

  • 简而言之:try / catch 仅对 terminating 错误起作用,而 cmdlet 报告 non-terminating则更为典型> 错误。要调用catch 块,必须通过传递-ErrorAction Stop 或预先设置$ErrorActionPreference = 'Stop' 将非终止错误提升为终止错误。有关更多信息,请参阅链接的帖子。

标签: powershell error-handling try-catch try-catch-finally


【解决方案1】:

您需要将-ErrorAction Stop 开关添加到您的Get-ItemPropertyNew-ItemProperty 行。有时命令会抛出一个非致命错误,并且catch 不会被调用。为确保您将落入您的catch,请添加上述开关。

【讨论】:

  • 很遗憾,这没有得到更好的记录 - 在我发现这是答案之前,我无法告诉你我有多接近秃顶......
  • 确实,@JeffZeitlin;创建一个关于错误处理的概念性帮助主题是很久以前提出的;与此同时,还有this summary of PowerShell's bewilderingly complex error handling。马修,如果您以后再次看到这个问题的变体,请将它们提名为链接帖子的副本。
  • 这是第二次发生了,mklement0。你能建议我可以用来找到这些帖子链接的策略吗?作为新来的,我不熟悉“标准答案”......我只是想帮忙。谢谢。
  • 对于“多态”问题,没有很好的方法来定位重复项,但您可以搜索问题的非特定元素并尝试通过这种方式缩小潜在的重复项。搜索词[powershell] try catch not working 将产生stackoverflow.com/… - 现在我已经运行了这个,我看到这个问题已经存在多少重复(它们都应该被链接)。我还保留有关反复出现的问题及其“规范”答案的个人笔记;识别合适的链接也需要练习。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多