繁体   English   中英

从Python脚本运行PowerShell函数

[英]Run PowerShell function from Python script

我需要从Python脚本运行PowerShell函数。 .ps1和.py文件当前都位于同一目录中。 我想调用的函数在PowerShell脚本中。 我见过的大多数答案都是从Python运行整个PowerShell脚本。 在这种情况下,我正在尝试从Python脚本在PowerShell脚本中运行单个函数。

以下是PowerShell脚本示例:

# sample PowerShell
Function hello
{
    Write-Host "Hi from the hello function : )"
}

Function bye
{
    Write-Host "Goodbye"
}

Write-Host "PowerShell sample says hello."

和Python脚本:

import argparse
import subprocess as sp

parser = argparse.ArgumentParser(description='Sample call to PowerShell function from Python')
parser.add_argument('--functionToCall', metavar='-f', default='hello', help='Specify function to run')

args = parser.parse_args()

psResult = sp.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
'-ExecutionPolicy',
'Unrestricted',
'. ./samplePowerShell',
args.functionToCall],
stdout = sp.PIPE,
stderr = sp.PIPE)

output, error = psResult.communicate()
rc = psResult.returncode

print "Return code given to Python script is: " + str(rc)
print "\n\nstdout:\n\n" + str(output)
print "\n\nstderr: " + str(error)

所以,不知何故,我想运行PowerShell示例中的'hello()'或'bye()'函数。 知道如何将参数传递给函数也是很好的。 谢谢!

你想要两件事: 点源脚本 (据我所知)(类似于python的import)和subprocess.call

import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePowershell\";", "&hello"])

所以这里发生的是我们启动PowerShell,告诉它导入你的脚本,并使用分号来结束该语句。 然后我们可以执行更多命令,即hello。

您还想为函数添加参数,所以让我们使用上面文章中的参数(稍微修改):

Function addOne($intIN)
{
    Write-Host ($intIN + 1)
}

然后使用您想要的任何参数调用该函数,只要powershell可以处理该输入。 所以我们将上面的python修改为:

import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePowershell\";", "&addOne(10)"])

这给了我输出:

PowerShell sample says hello.
11

暂无
暂无

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

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