我想使用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_output
。run
已在Python 3.5中添加,建议在call
, check_call
或check_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)