hackerboi
hackerboi

Reputation: 31

Running Powershell script within Python

I have a Powershell script that is working and a Python script that is working. I would like to have the Python script run the powershell script for me. I am unable to download any packages because this is on a work computer.

I did look into this before asking and found/tried the following codes:

One:

import subprocess, sys

p = subprocess.Popen(‘powershell.exe -ExecutionPolicy RemoteSigned -file “file location”’, stdout=sys.stdout)
p.communicate()

Two:

import subprocess, sys

p = subprocess.run(‘powershell.exe -ExecutionPolicy RemoteSigned -file “file location”’, shell=True)
p.communicate()

This seems to be the answer on every Reddit/SO question I’ve seen so I’m unsure why it doesn’t work for me. Does anyone know how to fix this? Or any work around?

Thank you in advance!

Upvotes: 1

Views: 1545

Answers (1)

Or Atias
Or Atias

Reputation: 11

subprocess.run(["powershell", "-Command", cmd], capture_output=True)

On the cmd you can add what ever command you would like to run. Im currently working on a project that includes powershell script running via python and this method works fine for me. One problem though: If you declare this as a variable and you want to iterate through the output, it creates a list of chrs instead of lines(probably easy fix but I didnt have the time to think about a solution).

Upvotes: 1

Related Questions