首页 > 解决方案 > 系统在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

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

提前致谢。

标签: python-3.xpowershellsubprocessget-winevent

解决方案


我会使用run而不是check_output. run Python 3.5 中已添加,建议在call,check_callcheck_output. 请参阅另一个问题

run返回CompletedProcess此处记录的 a 。

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

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)

推荐阅读