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()」関数を実行したいと考えています。また、関数にパラメーターを渡す方法を知っておくとよいでしょう。ありがとう!