从Python脚本运行PowerShell函数
我需要在一个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()'函数。如果能知道如何给这个函数传递参数,那就更好了。谢谢!
3 个回答
1
在2023年6月5日,我在最新的 Windows 10 x64
上测试了 Python 3.10
:
# Auto-detect location of powershell ...
process = subprocess.Popen("where powershell", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
stdout, stderr = stdout.decode('utf-8'), stderr.decode('utf-8')
powershell_path = stdout.strip()
# ... then run Powershell command and display output.
process = subprocess.Popen(f"{powershell_path} echo 'Hello world!'", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
stdout, stderr = stdout.decode('utf-8'), stderr.decode('utf-8')
print(stdout)
输出结果:
Hello world!
这个脚本的好处是它可以自动找到powershell的位置,这样就避免了因为不同版本的Windows而出现的问题。
4
这里有一个简单快捷的方法来实现这个。
import os
os.system("powershell.exe echo hello world")
58
你想要做两件事:首先是点源脚本(据我所知,这个和python里的导入功能类似),其次是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