PowerShell Cookbook

Search

Categories

 

On this page

Archive

Blogroll

Disclaimer
I work for Microsoft.

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 214
This Year: 14
This Month: 1
This Week: 0
Comments: 522

Sign In

 Wednesday, July 12, 2006
Wednesday, July 12, 2006 11:29:39 PM (Pacific Daylight Time, UTC-07:00) ( )

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} }

Comments [0] | | # 
Name
E-mail
Home page

Comment (Some html is allowed: b, blockquote@cite, em, i, strike, strong, sub, super, u)  

Enter the code shown (prevents robots):