2

I have a simple autohotkey script

!+l:: RunWait, PowerShell -NoExit -C "Import-Module D:\projects\changescreensaver\changescreensaver.psm1; Set-ScreenSaverTimeout 1;"

But it won't let me load my ps profile or do the import-module and gives me an execution policy error:

Import-Module : File D:\projects\changescreensaver\changescreensaver.psm1 cannot be loaded because running scripts is
disabled on this system. For more information, see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170.

On my terminal, Get-ExecutionPolicy -List returns

C:\Users\someone>Get-ExecutionPolicy  -List

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine    RemoteSigned 

but within my script, returns

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine       Undefined

I can just pass it -ExecutionPolicy Bypass, but I'd still like to understand: Why are my ExecutionPolicy values different when invoking PS from AHK?

xdhmoore
  • 8,935
  • 11
  • 47
  • 90
  • 3
    No, but I realized that AHK is running 32-bit powershell, while my terminal is 64-bit, so I guess that's the problem. – xdhmoore Jun 22 '19 at 19:23

2 Answers2

4

You found the source of the problem - your AHK is 32-bit and therefore runs the 32-bit PowerShell executable, while your terminal (console window) runs the 64-bit executable - but let me add some background information.

In Windows PowerShell (unlike in PowerShell Core) the execution policies are stored in the registry, namely at:

  • LocalMachine scope:

    • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell, value ExecutionPolicy
  • CurrentUser scope:

    • HKEY_CURRENT_USER\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell, value ExecutionPolicy

While 32-bit and 64-bit applications share the same HKEY_CURRENT_USER hive, they have distinct HKEY_LOCAL_MACHINE\Software subtrees.

Therefore, only the LocalMachine scope has separate execution-policy values for the 32-bit and 64-bit executables.

In other words: If your execution policy were set at the user level (-Scope CurrentUser), the problem would not arise.

mklement0
  • 382,024
  • 64
  • 607
  • 775
2

Turns out my terminal was running 64-bit powershell while AHK was using 32-bit, discovered by running:

[Environment]::Is64BitProcess

based on this post.

xdhmoore
  • 8,935
  • 11
  • 47
  • 90