【问题标题】:Execution Policy error when running powershell script from autohotkey从 autohotkey 运行 powershell 脚本时出现执行策略错误
【发布时间】:2019-11-04 21:02:56
【问题描述】:

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

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

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 值不同?

【问题讨论】:

  • 不,但我意识到 AHK 运行的是 32 位的 powershell,而我的终端是 64 位的,所以我想这就是问题所在。

标签: powershell autohotkey executionpolicy


【解决方案1】:

You found the source of the problem - 您的 AHK 是 32 位,因此运行 32 位 PowerShell 可执行文件,而您的终端(控制台窗口)运行 64 位可执行文件 - 但让我添加一些背景信息。

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

  • 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 hive,但它们具有不同的HKEY_LOCAL_MACHINE\Software 子树

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

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

【讨论】:

    【解决方案2】:

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

    [Environment]::Is64BitProcess
    

    基于this post

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 2019-08-15
      • 2023-03-21
      • 2016-11-11
      • 2014-07-23
      相关资源
      最近更新 更多