简体   繁体   English

从Python调用PowerShell脚本

[英]Invoking a PowerShell script from Python

I'm trying to start a PowerShell script from python like this: 我正在尝试从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()

The problem is that I get the following error: 问题是我得到以下错误:

File C:\\Users\\sztomi\\workspace\\myproject\\buildxml.ps1 cannot be loaded because the execution of scripts is disabled on this system. 无法加载文件C:\\ Users \\ sztomi \\ workspace \\ myproject \\ buildxml.ps1,因为在此系统上禁用了脚本的执行。 Please see "get-help about_signing" for more details. 请参阅“获取有关about_signing的帮助”以了解更多详细信息。

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). 尽管事实上我很早以前确实在管理员运行的PS终端中通过键入Set-ExecutionPolicy Unrestriced启用了Powershell中运行的脚本的事实(然后再做一次,只是为了确保)。 The powershell executable is the same that the shortcut in start menu points to. powershell可执行文件与开始菜单中的快捷方式所指向的可执行文件相同。 Get-ExecutionPolicy correctly reports Unrestricted no matter if I ran PowerShell as admin or not. 无论我是否以管理员身份运行PowerShell, Get-ExecutionPolicy正确报告Unrestricted

How can I execute a PS script correctly from Python? 如何从Python正确执行PS脚本?

First, Set-ExecutionPolicy Unrestriced is on a per user basis, and a per bitness basis (32-bit is different than 64-bit). 首先, Set-ExecutionPolicy Unrestriced是基于每个用户和每个位(32位与64位不同)的。

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()

Apparently you can access the 64-bit PowerShell from 32-bit PowerShell with this path (thanks to @eryksun in comments): 显然,您可以使用以下路径从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')

For those of us who wanted to know how to display the values of arg1, arg2 and arg3 after it was passed to powershell, all you need to do is: 对于我们这些想知道在传递给powershell之后如何显示arg1,arg2和arg3的值的人,您要做的就是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM