Home:ALL Converter>Run PowerShell function from Python script

Run PowerShell function from Python script

Ask Time:2013-01-25T03:05:02         Author:H_H

Json Formatter

I have a need to run a PowerShell function from a Python script. Both the .ps1 and the .py files currently live in the same directory. The functions I want to call are in the PowerShell script. Most answers I've seen are for running entire PowerShell scripts from Python. In this case, I'm trying to run an individual function within a PowerShell script from a Python script.

Here is the sample PowerShell script:

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

Function bye
{
    Write-Host "Goodbye"
}

Write-Host "PowerShell sample says hello."

and the Python script:

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)

So, somehow, I want to run the 'hello()' or the 'bye()' function that is in the PowerShell sample. It would also be nice to know how to pass in parameters to the function. Thanks!

Author:H_H,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/14508809/run-powershell-function-from-python-script
Adam R. Grey :

You want two things: dot source the script (which is (as far as I know) similar to python's import), and subprocess.call.\n\nimport subprocess\nsubprocess.call([\"C:\\\\WINDOWS\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe\", \". \\\"./SamplePowershell\\\";\", \"&hello\"])\n\n\nso what happens here is that we start up powershell, tell it to import your script, and use a semicolon to end that statement. Then we can execute more commands, namely, hello.\n\nYou also want to add parameters to the functions, so let's use the one from the article above (modified slightly): \n\nFunction addOne($intIN)\n{\n Write-Host ($intIN + 1)\n}\n\n\nand then call the function with whatever parameter you want, as long as powershell can handle that input. So we'll modify the above python to:\n\nimport subprocess\nsubprocess.call([\"C:\\\\WINDOWS\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe\", \". \\\"./SamplePowershell\\\";\", \"&addOne(10)\"])\n\n\nthis gives me the output:\n\nPowerShell sample says hello.\n11\n",
2013-01-28T02:32:01
yy