Maz*_*zda 3 error-handling powershell try-catch try-catch-finally
我正在尝试编写一个简单的 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"
}
Run Code Online (Sandbox Code Playgroud)
只要注册表路径正确,它就可以正常工作,但如果我将注册表文件夹 ...\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], ItemNotFoundException + ExcellentQualifiedErrorId : 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 ... + ~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 类别信息:未找到对象: (HKLM:\System\Cu...etBT\Parameters:String) [New-ItemProperty]、ItemNotFoundException + ExcellentQualifiedErrorId : PathNotFound、Microsoft.PowerShell.Commands.NewItemPropertyCommand
我已经尝试过仅使用Catch {}以及Catch [System.Management.Automation.ItemNotFoundException].
请指教。
您需要将-ErrorAction Stop开关添加到您的Get-ItemProperty和New-ItemProperty线路中。有时命令会抛出非致命错误,并且catch不会被调用。为了确保你会陷入你的catch,请添加上面的开关。