13

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"}')
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Deepak Kapri
  • 141
  • 1
  • 1
  • 3
  • 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

15

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
  • 306
  • 1
  • 8
  • 1
    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
  • 2
    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
  • 5
    Don't hardcode the location of `powershell.exe`. – cowlinator Sep 30 '21 at 04:13
  • @cowlinator could you explain or point me to a description of why you wouldn't do that? You got some upvotes so I feel I am in the wrong if I do it. – chris dorn Oct 07 '22 at 18:49
  • 1
    @chrisdorn , powershell is at various locations on various versions of Windows. See https://www.powershelladmin.com/wiki/PowerShell_Executables_File_System_Locations.php . Also, not all windows installations are located at `C:\Windows`. (That's why `%SystemRoot%` exists). One simple solution is to use `where powershell`. – cowlinator Oct 07 '22 at 22:01
  • This fails to run the command in the background in the latest version of PowerShell January 2023. The command runs in the foreground, which is not better than what we were getting before we tried the approach given in this answer. – CodeMed Jan 27 '23 at 20:13