从 Python 调用 PowerShell 脚本 [英] Invoking a PowerShell script from Python

查看:77
本文介绍了从 Python 调用 PowerShell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 python 启动一个 PowerShell 脚本,如下所示:

I'm trying to start a PowerShell script from python like this:

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

问题是我收到以下错误:

The problem is that I get the following error:

文件C:\Users\sztomi\workspace\myproject\buildxml.ps1无法加载,因为在此上禁用了脚本的执行系统.有关详细信息,请参阅get-help about_signing".

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 Unrestricted 启用了在 Powershell 中运行脚本的事实(并且再次这样做,只是为了确保).powershell 可执行文件与开始菜单中的快捷方式指向的相同.无论我是否以管理员身份运行 PowerShell,Get-ExecutionPolicy 都会正确报告 Unrestricted.

DESPITE the fact that I did enable running scripts in Powershell a long time ago by typing Set-ExecutionPolicy Unrestriced in an administrator-ran PS terminal (and did again, just to make sure). The powershell executable is the same that the shortcut in start menu points to. Get-ExecutionPolicy correctly reports Unrestricted no matter if I ran PowerShell as admin or not.

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

How can I execute a PS script correctly from Python?

推荐答案

首先,Set-ExecutionPolicy Unrestricted 是基于每个用户的,基于每个比特的(32 位不同于 64-位).

First, Set-ExecutionPolicy Unrestriced is on a per user basis, and a per bitness basis (32-bit is different than 64-bit).

其次,您可以从命令行覆盖执行策略.

Second, you can override the execution policy from the command line.

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 在评论中):

Apparently you can access the 64-bit PowerShell from 32-bit PowerShell with this path (thanks to @eryksun in comments):

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

这篇关于从 Python 调用 PowerShell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆