2

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?

rtf
  • 884
  • 2
  • 16
  • 30

1 Answers1

1

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.

rtf
  • 884
  • 2
  • 16
  • 30