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.
Posted on March 6, 2012, in WMF (Powershell/WinRM) and tagged access denied, powershell, reg load, reg unload, registry, Windows PowerShell. Bookmark the permalink. 3 Comments.
ingenious
Came across the same problem. Glad that I found this. Thanks a million!!!
Pingback: Set Up a Lab with Windows PowerShell and Free Microsoft Software: Part 4 - Hey, Scripting Guy! Blog - Site Home - TechNet Blogs