2

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

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

但它不会让我加载我的 ps 配置文件或执行 import-module 并给我一个执行策略错误:

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返回

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

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

但在我的脚本中,返回

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

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

4

2 回答 2

4

您找到了问题的根源- 您的 AHK 是 32 位,因此运行 32 位 PowerShell 可执行文件,而您的终端(控制台窗口)运行 64 位可执行文件 - 但让我添加一些背景信息。

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

  • LocalMachine范围:

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

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

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

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

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

于 2019-06-22T20:40:53.577 回答
2

结果我的终端运行的是 64 位的 powershell,而 AHK 使用的是 32 位,通过运行发现:

[Environment]::Is64BitProcess

基于这篇文章

于 2019-06-22T19:25:51.353 回答