Search code examples
powershellregistry

Find Registry key name based on a value? PowerShell


I am trying to find the registry key name based a value. In the key value, it has string (REG_SZ) like Version22.r2 (Name of this String value is "Version"). I have this under a specific path HKEY_CURRENT_USER\Software\Microsoft\xxxxxx. So, I want to look for the value Version22.r2 under HKEY_CURRENT_USER\Software\Microsoft\, if it is found, I want to find the key name (xxxxx).

Tried, it gives no output (what am i missing?!) (Get-ItemProperty 'HKCU:\Software\Microsoft' -ErrorAction SilentlyContinue | Where-Object {$_ -like "*Version22.r2*"}).PSChildName


Solution

  • Use Get-ChildItem -Recurse to discover all the relevant keys, then use Where-Object nested in Where-Object to inspect the string values attached to each and only filter in those keys that have at least one such value:

    Get-ChildItem HKLM:\SOFTWARE\Microsoft\ -Recurse |Where-Object {
      # assign current key to a local variable so we can reference it later
      $key = $_
      # now filter all the attached values based on type and content
      @($key.GetValueNames() |Where-Object {
        # first test that the value is a string ...
        $key.GetValueKind($_) -eq [Microsoft.Win32.RegistryValueKind]::String -and 
        # ... and then inspect the value
        $key.GetValue($_) -eq 'Version22.r2'
      } |Select -First 1).Count
    }