Skip to content Skip to sidebar Skip to footer

How To Run A Powershell Function Through A Python Script

I am trying to create a translator-type program in Python (this is 2.7, if that is important). I want to receive user input, translate it, and then print their output to the screen

Solution 1:

Your parameter construction is off. You want to run the following commandline in PowerShell:

. "./1337Export.ps1"; & export

which basically means "dot-source (IOW import) the script 1337Export.ps1 from the current working directory, then call (&) the function export".

The cleanest way to do this is to put the statement in a scriptblock:

&{. "./1337Export.ps1"; & export}

and pass that scriptblock as a single argument, so your Python statement should look like this:

subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", '-Command', '&{. "./1337Export.ps1"; & export}'])

Of course you need to make sure that 1337Export.ps1 actually exists in the current working directory when you execute the Python script.

Solution 2:

You have to do two things:

1)dot source the script (which is similar to python's import), and

2)subprocess.call.

import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePS\";", "&export"])

Note: I have assumed that both the .py and .ps1 are residing in the same directory and the name of the powershell script is "SamplePS" and from that script I am using the function "export"

Hope it helps

Post a Comment for "How To Run A Powershell Function Through A Python Script"