从Python调用PowerShell脚本

2024-06-30 15:05:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从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()

问题是我得到以下错误:

File C:\Users\sztomi\workspace\myproject\buildxml.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.

尽管很久以前我确实通过在管理员运行的PS终端中键入Set-ExecutionPolicy Unrestriced来启用在Powershell中运行脚本(为了确保这一点,我再次启用了)。powershell可执行文件与“开始”菜单中的快捷方式指向的相同。Get-ExecutionPolicy正确报告Unrestricted无论我是否以管理员身份运行PowerShell。

如何从Python正确执行PS脚本?


Tags: 脚本windows管理员exepssubprocesspopenpowershell
1条回答
网友
1楼 · 发布于 2024-06-30 15:05:41

首先,Set-ExecutionPolicy Unrestriced是基于每个用户的,并且是基于每位的(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')

相关问题 更多 >