我需要从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."
Run Code Online (Sandbox Code Playgroud)
和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 …Run Code Online (Sandbox Code Playgroud)