15

I want to execute the below commands from Python, but I'm not getting any output:

get-winevent -logname Microsoft-Windows-TerminalServices-LocalSessionManager/Operational -ComputerName $env:COMPUTERNAME | where {$_.Id -eq "21"}

I found some solutions as below, but they are also not running successfully:

subprocess.Popen('powershell.exe [get-winevent -logname Microsoft-Windows-TerminalServices-LocalSessionManager/Operational -ComputerName $env:COMPUTERNAME] | where {$_.Id -eq "21"}')
1

1 Answer 1

18

Using the subprocess library it's possible to run CMD commands within Python. In order to run powershell commands, all you'd need to do is execute C:\Windows\System32\powershell.exe and pass through the arguments.

Here's some example code to try:

import subprocess

subprocess.call('C:\Windows\System32\powershell.exe Get-Process', shell=True)

You can replace "Get-Process" with the PowerShell command you need

Sign up to request clarification or add additional context in comments.

7 Comments

Doing this returns the following error message in Python 3.8: 'C:\Windows\System32\powershell.exe' is not recognized as an internal or external command, operable program or batch file. Removing the directory for powershell and just having powershell.exe fixed this issue.
That means the executable "C:\Windows\System32\powershell.exe" cannot be found. Figure out where the powershell executable is located on your machine and change the directory accordingly.
Ahh yes, good point. I usually side-step any directory issues when scheduling powershell by using "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" but didn't think to do that here. Thanks!
Don't hardcode the location of powershell.exe.
@chrisdorn , powershell is at various locations on various versions of Windows. See powershelladmin.com/wiki/… . Also, not all windows installations are located at C:\Windows. (That's why %SystemRoot% exists). One simple solution is to use where powershell.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.