Python无法从PowerShell获取输出

问题描述

我正在尝试使用此代码获取推入python的SCCM中的Action列表,但我得到的所有内容都是一个空字节字符串。

count = r"""
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
  $arguments = "& '" +$myinvocation.mycommand.deFinition + "'"
  start-process powershell -Verb runAs -ArgumentList $arguments
  Break
}

$CMGR = New-Object -ComObject Cpapplet.CpappletMgr

$ClientActions = Out-String ($CMGR.GetClientActions() | Select Name).count
$ClientActions
"""

def runPS(command):
    import subprocess
    process=subprocess.run(["powershell","-ExecutionPolicy","Bypass",command],stdout=subprocess.PIPE);
    print(process.stdout)

所有这些输出b''

我在做什么错??

编辑:我想通了一部分。这是因为它在技术上运行了另一个Powershell(Python >> Powershell >> Admin Powershell),而第二个并没有将其值返回给第一个。 (Python Powershell >> Admin Powershell)

解决方法

我建议在这里使用check_output()而不是run()。这样,您就可以从子进程中检测到非零的退出代码。 More information here。 Powershell可能由于某些原因而失败,但是您没有捕获stderr或检查返回码。

像这样的东西可能更健壮:

def runPS(command):
    import subprocess
    output = subprocess.check_output(["powershell","-ExecutionPolicy","Bypass",command])
    return output

编辑:我想通了一部分。这是因为它在技术上运行了另一个Powershell(Python >> Powershell >> Admin Powershell),而第二个并没有将其值返回给第一个。 (Python Powershell >> Admin Powershell)

嗯。抱歉,我不知道Powershell,所以我无法为您提供那一半。