在Python之外执行PowerShell脚本

2024-06-30 15:42:15 发布

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

我试图运行一种同时使用Python和powershell脚本的应用程序。我已经编写了Python脚本和powershell脚本,它们可以同时工作,但彼此独立。我要做的是创建一个Python程序来启动它们,有没有办法?谢谢! 作为一个更大的脚本的一部分,我现在拥有的是:

import subprocess
autom = r"C:\Users\mrmostacho\Desktop\Robot\Autom.ps1","-ExecutionPolicy","Unrestricted"
powershell = r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
subprocess.Popen("%s %s" % (powershell, autom,))

Tags: import程序脚本应用程序robotuserssubprocessdesktop
1条回答
网友
1楼 · 发布于 2024-06-30 15:42:15

我认为您不希望"-ExecutionPolicy","Unrestricted"作为脚本参数,而是希望设置powershell执行策略以允许脚本的执行。因此,您应该在实际脚本之前传递这些参数。在

第二:仅仅将脚本作为参数传递给powershell.exe(这样,脚本名被解释为Powershell命令,并且必须根据Powershell引用规则对名称进行转义)。相反,脚本名应该在-File参数之后给出。来自online documentation

-File []

Runs the specified script in the local scope ("dot-sourced"), so that the functions and variables that the script creates are available in the current session. Enter the script file path and any parameters. File must be the last parameter in the command, because all characters typed after the File parameter name are interpreted as the script file path followed by the script parameters.

You can include the parameters of a script, and parameter values, in the value of the File parameter. For example: -File .\Get-Script.ps1 -Domain Central

Typically, the switch parameters of a script are either included or omitted. For example, the following command uses the All parameter of the Get-Script.ps1 script file: -File .\Get-Script.ps1 -All

In rare cases, you might need to provide a Boolean value for a switch parameter. To provide a Boolean value for a switch parameter in the value of the File parameter, enclose the parameter name and value in curly braces, such as the following: -File .\Get-Script.ps1 {-All:$False}.

第三:由于cdarke已经注释过了,最好使用列表而不是字符串作为Popen的参数。这样就不必担心Windows上的CommandLine parsing。在

总而言之,这应该是正确的选择。(用小测试脚本测试。)

import subprocess
autom = r"C:\Users\mrmostacho\Desktop\Robot\Autom.ps1"
powershell = r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
subprocess.Popen([powershell,"-ExecutionPolicy","Unrestricted","-File", autom])

如果需要将参数传递给脚本,请按如下方式执行:

^{pr2}$

相关问题 更多 >