How can I to run Windows PowerShell commands from Python? [duplicate]

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

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

4

You Might Also Like