I am trying to write a simple PowerShell code to create a registry key, then use TRY and CATCH to handle/catch any potential exceptions that may occur. As a test scenario, I am expecting to get "Script failed to create the registry key" if I modify the registry path. Unfortunately, the TRY/CATCH error handling function doesn't work for me and except the error itself nothing shows up in the console.
$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"
}
It works fine as long as the registry path is correct but if I rename the registry folder ...\NetBT\Parameters to ...\NetBT\Parameters1, I would only see:
Get-ItemProperty : Cannot find path 'HKLM:\System\CurrentControlSet\Services\NetBT\Parameters' because it does not exist. At 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 tion + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemPropertyCommand
New-ItemProperty : Cannot find path 'HKLM:\System\CurrentControlSet\Services\NetBT\Parameters' because it does not exist. At 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 tion + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.NewItemPropertyCommand
I have already tried to use only Catch {}
as well as Catch [System.Management.Automation.ItemNotFoundException]
.
Please advice.