Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}')
like image 435
Deepak Kapri Avatar asked Jan 24 '19 03:01

Deepak Kapri


1 Answers

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

like image 191
TimeLoad Avatar answered Oct 20 '22 04:10

TimeLoad