Search code examples
python-3.xpowershellsubprocessget-winevent

The system cannot find the file specified error in python


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.


Solution

  • 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)