简体   繁体   中英

Execution Policy error when running powershell script from autohotkey

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?

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.

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

[Environment]::Is64BitProcess

based on this post .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM