【发布时间】: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