I’m trying to get the key name from a registry key, that has a property that matches certain text.
That key name will then be used to find the correct MSI file to run with MSIExec.exe to uninstall the software.
The following works as expected when there is a key found but fails when no key is found.
Try{
$ErrorActionPreference = "SilentlyContinue"
$AlphaRegistry = Get-ItemProperty -Path 'HKLM:SOFTWAREMicrosoftWindowsCurrentVersionUninstall*' | Where-Object{$_.DisplayName -like "*Alpha*"}
switch ($AlphaRegistry.PSChildName.trim('{}')) {
FB917EA8-1B7F-4347-A05F-7AF03DF0577D {$InstallerMSI = 'setup17_6.msi'}
C75C2499-0D4D-6789-BEB2-32CA03BF8880 {$InstallerMSI = 'setup17_5.msi'}
68C6A4F3-3422-467D-AAAA-924282DC5365 {$InstallerMSI = 'set17_4_1.msi'}
Default {Add-LogContent "Unable to identify msi file to uninstall Alpha version installed. Unable to progress"
[System.Environment]::Exit(1)}}
# Uninstall code using $InstallerMSI here
}
catch{
$ErrorMessage = " Error during removal. Unable to continue. " + $Error[0].Exception.Message
Add-LogContent -LogText $ErrorMessage
[System.Environment]::Exit(1)
}
I know I should test for null after $AlphaRegistry = Get-ItemProperty -Path 'HKLM:SOFTWAREMicrosoftWindowsCurrentVersionUninstall*' | Where-Object{$_.DisplayName -like "*Alpha*"}
but no matter what I try I can’t get past that line. I always get the error ‘You cannot call a method on a null-valued expression’. I don’t even know what method is being called on that line.
I’ve tried taking the population of $AlphaRegistry out the equation and I still get the same error so know it isn’t the assignment of null to the variable.
I’ve tried the same code outside the Try-Catch block and I don’t get an error and therefore assume my implementation of the Try-Catch block is the cause.
I’ve also tried various settings for $ErrorActionPreference, both inside and before the Try-Catch block.
I want to use the error handling for the uninstall code I’ve removed, so ideally need a way to make the search work within the Try-Catch block.
Any pointer in the right direction would be appreciated thanks.
Tony is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.