Phyton Run PowerShell function from Python script call powershell function from python,run powershell function from python

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!

Answer:1



  1. call powershell function from python
  2. run powershell function from python script
  3. run powershell function from python
  4. call python function from powershell script

A top class called Parametric is used to create objects which can have parameters associated with them: class Parametric(object): def __init__(self, name): self.name = name self.pars = [] class ...

A top class called Parametric is used to create objects which can have parameters associated with them: class Parametric(object): def __init__(self, name): self.name = name self.pars = [] class ...

I'm looking for an equivalent to GetTickCount() on Linux. Presently I am using Python's time.time() which presumably calls through to gettimeofday(). My concern is that the time returned (the unix ...

I'm looking for an equivalent to GetTickCount() on Linux. Presently I am using Python's time.time() which presumably calls through to gettimeofday(). My concern is that the time returned (the unix ...