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?