0

The easiest way to execute PowerShell commands using python is invoking a cmd command using: Example: powershell -c "Get-VM"

But, this method is inefficient when being used thousands of times, since each call invokes a PowerShell session so it takes a few precious seconds (times a few thousands it may sum to hours).

What I would like to achieve is to reduce this execution time by having PowerShell session open in the background. I have explored a few methods and I would like to know if there are other possibilities.

The best method I found so far (working, but seems like a somewhat "dirty" solution)

  • Having a PowerShell session listening to a certain file. If the file exists, the PS session will immediately execute the command in that file and then delete this file, and store the output in a separate file. Python will handle creating and deleting the file and reading the output file.

Few things:

  • Output is mandatory
  • Commands have to be able to be executed on separate time periods and cannot be executed together.
  • The entire point is to eliminate the few seconds it takes to call powershell -c "...", so what ever the solution is, the command execution has to eliminate that issue.

Do you think there a better way?

Idan878
  • 21
  • 7
  • 1
    You'll need to invoke the PowerShell CLI with `-c -` and then feed commands to it via _stdin_ - see [this answer](https://stackoverflow.com/a/69036873/45375) (does _not_ show a Python solution, but contains background information). – mklement0 Nov 24 '21 at 22:55
  • You could perhaps achieve that with the `subprocess` module from the Python standard library? `subprocess.run(args="powershell Get-VM", shell=True, capture_output=False)` – Laurent Nov 27 '21 at 15:53

0 Answers0