Run PowerShell function from Python script Run PowerShell function from Python script powershell powershell

Run PowerShell function from Python script


You want two things: dot source the script (which is (as far as I know) similar to python's import), and subprocess.call.

import subprocesssubprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePowershell\";", "&hello"])

so 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.

You also want to add parameters to the functions, so let's use the one from the article above (modified slightly):

Function addOne($intIN){    Write-Host ($intIN + 1)}

and 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:

import subprocesssubprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePowershell\";", "&addOne(10)"])

this gives me the output:

PowerShell sample says hello.11


Here is a short and simple way to do that

import osos.system("powershell.exe echo hello world")