0

I want to initialise a powershell subprocess and be able to send commands to it and receive its output using Python on Windows.

Please can someone help with simple examples? I have gone through almost every other post similar to this on here but haven't had any luck with my specific problem...

I am to run this code to automate a current manual process conducted on Powershell.

This is a high level look at what I want to achieve using Python

  1. I want to launch a powershell session using Python
  2. Then CD into a directory
  3. Run a powershell script in that directory
  4. Display/retrieve all outputs
  5. And pass new commands in the same session, again, whilst capturing outputs

So far all I have is the following code which launches powershell and runs a .ps1 file by giving directory. I'm not sure how to proceed from here or if this is even the best approach given the steps I need to undertake shown above.

p = subprocess.Popen(["powershell.exe", Powershell.exe -executionpolicy remotesigned -File 'G:\My Documents\helloworld.ps1';"]. stdout=sys.stdout)

p.communicate()

After running the above code, python terminal displays the message 'Test Message' correctly

  • 2
    Can you share the code you wrote that isn't working? – dfundako Jan 20 '21 at 16:22
  • @dfundako Hi, I have just added the code I have so far in the body of the question. – oliveottoman Jan 20 '21 at 16:32
  • What did you search for? Either via eh SO search box above or via the web as a whole. Running PowerShell from Python, C#, etc., is a common use case. Lot's of examples exist. ['run PowerShell code from python'](https://duckduckgo.com/?q=%27run+Powershell+code+from+python%27&t=h_&ia=web&iai=r1-0&page=1&sexp=%7B%22cdrexp%22%3A%22b%22%2C%22artexp%22%3A%22b%22%2C%22prodexp%22%3A%22b%22%2C%22prdsdexp%22%3A%22c%22%2C%22biaexp%22%3A%22b%22%2C%22msvrtexp%22%3A%22b%22%2C%22djsdexp%22%3A%22a%22%7D) Several SO hits from that link. So, this can be viewed as a duplicate question. – postanote Jan 20 '21 at 17:13
  • @postanote I checked every single thread related to this on SO and many pages on google over the past few days, and the solutions proposed haven't worked for me unfortunately. – oliveottoman Jan 20 '21 at 17:22
  • Hummm, OoooK... Are you doing this locally or remotely? When you call PowerShell console host to run code, from any language, it will open PowerShell, run the code, and close, returning you back to where you started. Unless you tell PowerShell not to close `NoExit`, there is no PowerShell session open. – postanote Jan 20 '21 at 17:31

0 Answers0