-2

i want to run following power-shell command using python script:

timedetail = subprocess.check_output('powershell.exe Get-WinEvent -LogName Microsoft-Windows-TerminalServices-LocalSessionManager/Operational  | Where { ($_.ID -eq "25" -or  $_.ID -eq "21") -and ($_.TimeCreated -gt [datetime]::Today.AddDays(-2))} |Select TimeCreated , Message | sort-Object -Property TimeCreated -Unique | Format-List', startupinfo=st_inf,shell=False,stderr=subprocess.PIPE, stdin=subprocess.PIPE).decode('ANSI').strip().splitlines()

but this is not working with python code this is displaying an error:

[WinError 2] The system cannot find the file specified

anyone can help how to run powershell command using python code?

thanks in advance.

Shreya
  • 35
  • 2
  • 12
  • It looks like you want to read events from the Windows event Log, did you try the `win32evtlog` module from `pywin32`? (See also https://stackoverflow.com/questions/30287121/reading-windows-event-log-in-python-using-pywin32-win32evtlog-module) – Xtrem532 Jan 15 '21 at 10:23

1 Answers1

2

I would use run instead of check_output. run has been added in Python 3.5 and it is recommended to use it prior to call, check_call or check_output. See this other question.

run returns a CompletedProcess that is documented here.

Here is an updated version of your script:

import subprocess


def run_powershell_command(command):
    completed = subprocess.run(["powershell", "-Command", command], capture_output=True)
    return completed


get_logs_command = 'Get-WinEvent -LogName Microsoft-Windows-TerminalServices-LocalSessionManager/Operational  | Where { ($_.ID -eq "25" -or  $_.ID -eq "21") -and ($_.TimeCreated -gt [datetime]::Today.AddDays(-2))} |Select TimeCreated , Message | sort-Object -Property TimeCreated -Unique | Format-List'
result = run_powershell_command(get_logs_command)

for line in result.stdout.splitlines():
    print(line)
Munshine
  • 402
  • 3
  • 14