Testing for the Presence of a Registry Key and Value

There are a number of different ways to test for the presence of a registry key and value in PowerShell. Here’s how I like to go about it. We’ll use an example key HKLM:\SOFTWARE\TestSoftware with a single value Version:

Check for the key

You can use the Test-Path cmdlet to check for the key, but not for specific values within a key. For example


Test-Path 'HKLM:\\SOFTWARE\\TestSoftware'

but not


Test-Path 'HKLM:\\SOFTWARE\\TestSoftware\\Version'

So for the value we need to work a bit harder. Using the below function we can see if Get-ItemProperty contains the value or not.


function Test-RegistryValue {

  param (
  
  [parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]$Path,
  
  [parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]$Value
)
  
  try {
  
    Get-ItemProperty -Path $Path -ErrorAction Stop | Select-Object -ExpandProperty $Value -ErrorAction Stop | Out-Null
    return $true
  }
  
  catch {
  
    return $false
  
  }

}

So for our example:


Test-RegistryValue -Path 'HKLM:\\SOFTWARE\\TestSoftware' -Value 'Version' 
Test-RegistryValue -Path 'HKLM:\\SOFTWARE\\TestSoftware' -Value 'Banana'