You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PowerShell输出的AD活跃用户列表转为Python数组

解决Python调用PowerShell获取AD用户列表并转为数组的问题

问题分析

你当前的代码存在几个核心问题:

  • 把stdout重定向到sys.stdout,导致输出直接打印到控制台,Python脚本无法捕获数据;
  • 直接将Popen进程对象赋值给变量,打印的自然是进程的描述信息,而非脚本输出内容;
  • 使用time.sleep(7)等待进程完成不可靠,进程可能提前结束或超时。

修正后的代码

import subprocess

def gebruikers_ophalen():
    # 调用PowerShell脚本,捕获标准输出和错误输出
    p = subprocess.Popen(
        ["powershell.exe", "-ExecutionPolicy", "Bypass", "-File", "C:/file_locationLis/script.ps1"],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        encoding="utf-8"
    )
    # 等待进程执行完成,获取输出内容
    stdout, stderr = p.communicate()
    
    # 处理输出:按行分割、去除空白字符、过滤空行
    geb_lijst = [line.strip() for line in stdout.splitlines() if line.strip()]
    
    # 若有错误信息,打印便于排查
    if stderr:
        print(f"执行错误: {stderr}")
    
    return geb_lijst

# 调用函数并获取用户数组
active_users = gebruikers_ophalen()
print(active_users)

关键说明

  • 捕获输出:用subprocess.PIPE替代stdout=sys.stdout,让Python能读取PowerShell脚本的输出内容;
  • 可靠等待:communicate()方法会自动等待进程执行完毕,避免time.sleep的不确定性;
  • 编码处理:text=True和encoding="utf-8"确保输出以文本格式读取,避免乱码或字节串处理问题;
  • 输出清洗:通过列表推导式过滤空行和多余空格,得到干净的用户名数组;
  • PowerShell脚本注意:确保脚本中使用Write-Output输出用户列表(或直接输出对象,PowerShell默认会将对象转为字符串输出到stdout),不要用Write-Host(其输出不会被subprocess捕获)。

内容的提问来源于stack exchange,提问作者Hekkie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 00:20:24