从Python调用PowerShell脚本

17 投票
2 回答
28786 浏览
提问于 2025-04-16 22:40

我想从Python启动一个PowerShell脚本,代码是这样的:

psxmlgen = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
                             './buildxml.ps1',
                             arg1, arg2, arg3], cwd=os.getcwd())
result = psxmlgen.wait()

但是我遇到了一个问题,出现了以下错误:

文件 C:\Users\sztomi\workspace\myproject\buildxml.ps1 无法加载,因为系统禁用了脚本的执行。请查看“get-help about_signing”以获取更多信息。

尽管我很早之前就通过在管理员权限的PowerShell终端输入 Set-ExecutionPolicy Unrestricted 来启用脚本运行(而且我又做了一遍,以确保设置正确)。PowerShell的可执行文件和开始菜单快捷方式指向的是同一个。无论我是否以管理员身份运行PowerShell, Get-ExecutionPolicy 都正确显示为 Unrestricted

我该如何从Python正确执行一个PowerShell脚本呢?

2 个回答

1

对于那些想知道如何在传递参数到PowerShell后显示arg1、arg2和arg3的值的人,你只需要这样做:

Write-Host $args[0]
Write-Host $args[1]
Write-Host $args[2]
18

首先,Set-ExecutionPolicy Unrestricted 是针对每个用户的,而且在32位和64位系统上是不同的。

其次,你可以通过命令行来覆盖执行策略。

psxmlgen = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
                             '-ExecutionPolicy',
                             'Unrestricted',
                             './buildxml.ps1',
                             arg1, arg2, arg3], cwd=os.getcwd())
result = psxmlgen.wait()

显然,你可以通过这个路径从32位的PowerShell访问64位的PowerShell(感谢评论中的@eryksun提供的信息):

powershell64 = os.path.join(os.environ['SystemRoot'], 
    'SysNative' if platform.architecture()[0] == '32bit' else 'System32',
    'WindowsPowerShell', 'v1.0', 'powershell.exe')

撰写回答