简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM