我正在尝试编写一个简单的 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 …