3

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.

Mazda
  • 33
  • 1
  • 5
  • 2
    In short: `try` / `catch` only acts on _terminating_ errors, whereas it is far more typical for cmdlets to report _non-terminating_ errors. For the `catch` block to get invoked, non-terminating errors must be promoted to terminating ones by passing `-ErrorAction Stop` or by setting `$ErrorActionPreference = 'Stop'` beforehand. See the linked post for more information. – mklement0 Feb 10 '20 at 18:30

1 Answers1

5

You need to add the -ErrorAction Stop switch to your Get-ItemProperty and New-ItemProperty lines. Sometimes commands will throw a non-fatal error, and the catch doesn't get invoked. To ensure that you will fall into your catch, add the above switch.

Matthew
  • 1,096
  • 7
  • 12
  • 1
    It's really sad that this isn't better documented - I can't tell you how close to bald I got before I discovered this to be the answer... – Jeff Zeitlin Feb 10 '20 at 18:17
  • Indeed, @JeffZeitlin; creating a conceptual help topic about error handling was proposed quite a while ago; in the meantime, there's [this summary of PowerShell's bewilderingly complex error handling](https://github.com/PowerShell/PowerShell-Docs/issues/1583). Matthew, if you see a variations of this question again in the future, please nominate them as duplicates of the linked post. – mklement0 Feb 10 '20 at 18:26
  • This is the 2nd time that has happened, mklement0. Can you suggest strategies I can use to find these posts to link to? Being new here, I am unfamiliar with the "standard answers"...I just want to help. Thanks. – Matthew Feb 10 '20 at 18:32
  • With "polymorphic" problems there isn't a great way to locate duplicates, but you can search for the non-specific elements of the question and try to narrow potential duplicates down that way. Search term `[powershell] try catch not working` will yield https://stackoverflow.com/search?q=%5Bpowershell%5D+try+catch+not+working - and now that I've run this, I see how many more duplicates of this issue already exist (they should all be linked). I also keep personal notes on recurring problems and their "canonical" answers; recognizing the appropriate ones to link to also takes practice. – mklement0 Feb 10 '20 at 19:22