Bill Westrup
Bill Westrup

Reputation: 175

Powershell: Variable assignment triggers module import

This code works from the Powershell command line but generates an error when run from a script:

$key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced'
Set-ItemProperty $key Hidden 1

When I run it from my script, I get the following error:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer : The module 'HKEY_CURRENT_USER' could not be
loaded. For more information, run 'Import-Module HKEY_CURRENT_USER'.
At C:\Users\mybitch\Desktop\VSS-Customize-Desktop.ps1:19 char:6
+ $key=HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (HKEY_CURRENT_US...ersion\Explorer:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CouldNotAutoLoadModule

This is a simple assignment...Why would Powershell try to import HKEY_CURRENT_USER as a module? Why is the behavior so different from the Powershell command line?

Upvotes: 2

Views: 1393

Answers (2)

Luke
Luke

Reputation: 667

Make sure in the script you have the User Hive being loaded, for example if you are running it from a task scheduler you will need it to load a hive for it to have the effect that you want.

Upvotes: 0

latkin
latkin

Reputation: 16792

The error message betrays the problem. In your script, apparently you are doing this:

$key = HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer

That is an invalid assignment. You should be doing as you describe:

$key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced'

Upvotes: 5

Related Questions