运行 来自 autohotkey 的 powershell 脚本时执行策略错误

Execution Policy error when running powershell script from autohotkey

我有一个简单的自动热键脚本

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

但它不会让我加载我的 ps 配置文件或执行导入模块并给我一个执行策略错误:

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.

在我的终端上,Get-ExecutionPolicy -List returns

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

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

但在我的脚本中,returns

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

我可以传递它-ExecutionPolicy Bypass,但我仍然想了解:为什么从 AHK 调用 PS 时我的 ExecutionPolicy 值不同?

原来我的终端是 运行 64 位 powershell 而 AHK 使用的是 32 位,由 运行:

发现
[Environment]::Is64BitProcess

基于this post

- 你的 AHK 是 32 位的,因此运行 32 位的 PowerShell 可执行文件,而你的终端(控制台 window)运行 64 位的可执行文件 - 但让我添加一些背景资料。

Windows PowerShell 中(与 PowerShell Core 不同) 执行策略存储在注册表,即:

  • LocalMachine 范围:

    • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\ShellIds\Microsoft.PowerShell,价值ExecutionPolicy
  • CurrentUser 范围:

    • HKEY_CURRENT_USER\SOFTWARE\Microsoft\PowerShell\ShellIds\Microsoft.PowerShell,价值ExecutionPolicy

虽然 32 位和 64 位应用程序 共享相同的 HKEY_CURRENT_USER 配置单元,但它们 具有不同的 HKEY_LOCAL_MACHINE\Software 子树.

因此,只有 LocalMachine 作用域对 32 位和 64 位可执行文件具有单独的 execution-policy 值。

换句话说:如果你的执行策略设置在用户级别(-Scope CurrentUser),问题就不会出现。