Search code examples
powershellpowershell-5.0

PowerShell: Get registry key name given sub-key name & value


I'm trying to return a registry key name given sub-key name & value. For instance, if exists:

HKLM:\Software\key1\home1 home_val=C:\dir1
HKLM:\Software\key2\home2 home_val=C:\dir2

I want to be able to return the key name that has sub-key=home_val=C:\dir1

I'm ALMOST there but can't figure out how to return the key name. I've come up with the following:

Get-ItemPropertyValue -Path 'HKLM:\SOFTWARE\key*' -Name HOME_VAL | Select-Object -Property 'C:dir1'

Solution

  • Your code gives me this error...

    Get-ItemPropertyValue : Property HOME_VAL does not exist at path HKEY_LOCAL_MACHINE\SOFTWARE\key1

    ...when it encounters a key without a HOME_VAL value.

    This works for me to get the full key path...

    PS> $filterValueName = 'home_val'
    PS> $filterValueData = 'C:\dir1'
    PS> Get-ChildItem -Path 'HKLM:\SOFTWARE\key*' -Recurse `
            | Where-Object { ($_ | Get-ItemProperty -Name $filterValueName).$filterValueName -eq $filterValueData } `
            | Select-Object -ExpandProperty 'Name'
    HKEY_LOCAL_MACHINE\SOFTWARE\key1\home1
    

    That will enumerate all descendant keys beneath any HKLM:\SOFTWARE\key* keys, selecting those that have a value named home_val with data C:\dir1 and extracting their Name property. If you want the key name instead of its path you can select the PSChildName property instead.