9

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"}')
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Deepak Kapri
  • 101
  • 1
  • 1
  • 2
  • 1
    Please [format your code and sample input/output properly](http://meta.stackexchange.com/a/22189/248777). – mklement0 Jan 24 '19 at 03:35

1 Answers1

13

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

TimeLoad
  • 186
  • 8
  • 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. – Ryan Harris Jul 08 '20 at 19:26
  • 1
    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. – TimeLoad Nov 16 '20 at 02:45
  • 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! – Ryan Harris Nov 17 '20 at 14:07
  • 1
    Don't hardcode the location of `powershell.exe`. – cowlinator Sep 30 '21 at 04:13