Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
add comment

1 Answer

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
add comment

Your Answer

 
discard

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.