PowerShell Try Catch错误处理功能未显示我的自定义警告消息[重复]

问题描述 投票:0回答:1
我正在尝试编写简单的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+如果((((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-名称“ NodeType”-值2 ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~+ CategoryInfo:ObjectNotFound:(HKLM:\ System \ Cu ... etBT \ Parameters:String)[New-ItemProperty],ItemNotFoundExcep位置+ FullyQualifiedErrorId:PathNotFound,Microsoft.PowerShell.Commands.NewItemPropertyCommand

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

请咨询。

powershell error-handling try-catch try-catch-finally
1个回答
1
投票
您需要将-ErrorAction Stop开关添加到Get-ItemPropertyNew-ItemProperty行。有时命令会引发非致命错误,并且不会调用catch。为了确保您可以进入catch,请添加上述开关。
© www.soinside.com 2019 - 2024. All rights reserved.