$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.GetItemPropertyCommandNew-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]
。请咨询。
-ErrorAction Stop
开关添加到Get-ItemProperty
和New-ItemProperty
行。有时命令会引发非致命错误,并且不会调用catch
。为了确保您可以进入catch
,请添加上述开关。