如何从 python 运行 windows-powershell 命令? [英] How to run windows-powershell commands from python?

查看:118
本文介绍了如何从 python 运行 windows-powershell 命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 python 执行以下命令,但我没有得到输出:

I want to execute the below commands from python but I'm not getting output:

get-winevent -logname Microsoft-Windows-TerminalServices-LocalSessionManager/Operational -ComputerName $env:COMPUTERNAME | where {$_.Id -eq "21"}

我找到了以下一些解决方案,但它们也没有成功运行:

I found some solutions as below but they are also not running successfully:

subprocess.Popen('powershell.exe [get-winevent -logname Microsoft-Windows-TerminalServices-LocalSessionManager/Operational -ComputerName $env:COMPUTERNAME] | where {$_.Id -eq "21"}')

推荐答案

使用 subprocess 库可以在 Python 中运行 CMD 命令.为了运行 powershell 命令,您需要做的就是执行 C:\Windows\System32\powershell.exe 并传递参数.

Using the subprocess library it's possible to run CMD commands within Python. In order to run powershell commands, all you'd need to do is execute C:\Windows\System32\powershell.exe and pass through the arguments.

以下是一些可以尝试的示例代码:

Here's some example code to try:

import subprocess

subprocess.call('C:\Windows\System32\powershell.exe Get-Process', shell=True)

您可以将Get-Process"替换为您需要的 PowerShell 命令

You can replace "Get-Process" with the PowerShell command you need

这篇关于如何从 python 运行 windows-powershell 命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆