PowerShell: Loading and Unloading Registry Hives


PowerShell will by default expose your HKLM and HKCU hives via drives which work because of the Registry PSProvider.


get-psdrive

get-psprovider

Since we see that it’s the provider that allows us to map these hives we can take it a step further and map a hive from a file (update user hives on a remote system). The problem with this is that the Registry PSProvider doesn’t extend to files. However this doesn’t stop us.


reg load 'HKLM\TempUser' $ntuserlocation

cd hklm:\TempUser

gci

New-PSDrive -Name HKMyUser -PSProvider Registry -Root HKLM\TempUser

cd HKMyUser:\

gci

cd c:

Remove-PSDrive HKMyUser

reg unload hklm\TempUser

This all works great until we attempt to unload that hive file or in some cases the unload works ok but we still have handles to the hive file (you can use sysinternals Handle.exe to see this)

Why is that if we removed the drive and asked Reg.exe to unload the hive? The problem is that the system has not released the memory which still has pointers in to that file, preventing us from unloading the hive or stopping us from doing other things.

So whats the trick you ask?

Ask the system to clean up those references that are no longer in use.


[gc]::collect()

This uses the static method Collect from the GC class in .NET which is used for forcing the garbage collector to run and removing those unused references.

Advertisements

About jrich

I am the Solutions Architect for Apex Learning in Seattle WA. I've been working with computers since I was 13. Started programming when I was 14. Had my first IT job as tech support at an ISP at the age of 15 and became a network admin at the age of 17. Since then I've worked at a variety of small to mid size companies supporting, maintaining and developing all aspects of IT. Mostly working with Windows based networks but have recently been working with Solaris system as well. I created this blog mostly as a place for me to take my own notes, but also share things that I had a hard time finding the info for.

Posted on March 6, 2012, in WMF (Powershell/WinRM) and tagged , , , , , . Bookmark the permalink. 3 Comments.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: