How can I unload multiple registry hives in PowerShell? (Access Denied error)

Posted on

How can I unload multiple registry hives in PowerShell? (Access Denied error) – Managing your servers can streamline the performance of your team by allowing them to complete complex tasks faster. Plus, it can enable them to detect problems early on before they get out of hand and compromise your business. As a result, the risk of experiencing operational setbacks is drastically lower.

But the only way to make the most of your server management is to perform it correctly. And to help you do so, this article will share nine tips on improving your server management and fix some problem about windows, powershell, windows-registry, , .

I’ve loaded dozens of registry hives as HKLM:temp_$username. Now when I try to run ls HKLM:temp_* | %{reg unload $_} I get ERROR: Access is denied.

I’m running PowerShell with elevated priveleges and tried restarting PowerShell ISE to clear out variables. I still receive the error. I can unload the hives using the GUI, and I can run the command for individual hives (reg unload HKLMtemp_jimbob), so I’m a little perplexed as to why the command simply will not run for multiple hives.

What is causing the access denied error and how can I fix it?

Solution :

The command ls HKLM:temp_* is what’s causing the “access denied” error. Running this command is leaving every desired registry hive open and inaccessible to the reg program. It’s sort of a catch-22: without the list the hives cannot be unloaded, but the list cannot be used once obtained.

To work around this, use the Name property, which is a [System.String] versus a [Microsoft.Win32.RegistryKey]:

$foo = ls "hklm:temp_*" | Select -ExpandProperty Name
foreach($bar in $foo)
    reg unload $bar

Note that it must be two lines. Trying to pipe the output of Select will result in the same error.

If you still receive errors, it might be worth running garbage collection using [gc]::collect(), picking through Get-Variables, or restarting PowerShell ISE.

Leave a Reply

Your email address will not be published.