系统找不到python中指定的文件错误



我想使用python脚本运行以下power-shell命令:

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

但是python代码不能使用,这显示了一个错误:

[WinError 2] The system cannot find the file specified

任何人都可以帮助如何运行powershell命令使用python代码?

thanks in advance.

我会用run代替check_outputrun已在Python 3.5中添加,建议在call, check_callcheck_output之前使用它。参见另一个问题

run返回这里记录的CompletedProcess

这是你的脚本的更新版本:

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)

相关内容

  • 没有找到相关文章

最新更新