Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 HKLM\temp_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?

share|improve this question
up vote 0 down vote accepted

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.