How Do I Search the Registry for a Value in PowerShell?
The question came up recently in an internal discussion list, “How do I search the Registry for a value in PowerShell?”
In the FileSystem, we have the select-string cmdlet to do the hard work for you. We don’t have the equivalent yet for other stores, so unfortunately the answer is to write ‘grep’ from scratch. It’s manageable, though.
The key here is to think of registry key values like you would think of content in a file:
Directories have items, items have content.
Registry keys have properties, properties have values.
The way to get property values in PowerShell is the Get-ItemProperty cmdlet.
So:
cd HKCU:
Get-ChildItem . –rec –ea SilentlyContinue
Gets you all of the subkeys in the registry, just like you might get all of the files on your hard drive. We then pass that into the “Get-ItemPropery” cmdlet, to get the content of the properties:
| foreach { Get-ItemProperty –Path $_.PsPath }
To check for matches, we use the –match operator:
... (Get-ItemProperty -Path $_.PsPath) -match "evr.dll"
But that just outputs a bunch of “Yes” and “No” answers. We in fact want to output the key name if this matches, so we wrap that in an If statement and output the path:
... if( (Get-ItemProperty -Path $_.PsPath) -match "evr.dll") { $_.PsPath }
That gives us a script-like representation of:
######################################################################
##
## Search-RegistryKeyValues.ps1
## Search the registry keys from the current location and down for a
## given key value.
##
######################################################################
param([string] $searchText = $(throw "Please specify text to search for."))
gci . -rec -ea SilentlyContinue |
% {
if((get-itemproperty -Path $_.PsPath) -match $searchText)
{
$_.PsPath
}
}
Or a “one-liner” of:
gci . -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match "<SomeText>") { $_.PsPath} }