【问题标题】:Python calling Powershell commandsPython 调用 Powershell 命令
【发布时间】:2021-12-24 21:10:46
【问题描述】:

我正在构建一个调用 Powershell 来获取数据的 API。

当我使用 subprocess.check_output

运行命令时,除了 '*' 一切正常
powershell_call = json.loads(subprocess.check_output([
    'powershell.exe',
     f'{cmdlet_name} -Identity "{identity}" -Server {server} -Properties * | ConvertTo-Json -Depth {jsonDepth}'
]))

错误信息:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa2 in position 8110: invalid start byte

我试着把调用方式改成这样:

powershell_call = subprocess.Popen(
    [
        "powershell.exe",
        f'{cmdlet_name} -Identity "{identity}" -Server {server} -Properties * | ConvertTo-Json -Depth {jsonDepth}'
    ],
    shell=True,
    stdout = subprocess.PIPE,
    encoding = 'utf-8',
    universal_newlines = True
)

但它给出了相同的错误信息。

在通过子进程调用 PowerShell 时有什么方法可以传递星号?

--- 编辑 ---

原来我只需要将 subprocess.check_output 更改为 subprocess.getoutput

【问题讨论】:

  • 看起来您的脚本需要来自 PowerShell 的 UTF-8 编码输出。为此,您必须将控制台的输出代码页设置为65001。 (很可能是命令的 output 是问题所在,而不是 * char. int 命令本身)。
  • 太棒了,感谢您的回复!我查找了您所写内容的信息,发现我需要做的就是将 subprocess.check_output 更改为 subprocess.getoutput。再次感谢!

标签: python powershell


【解决方案1】:

原来如此,我只需要将 subprocess.check_output 更改为 subprocess.getoutput

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
  • 2020-11-17
  • 2013-08-19
  • 1970-01-01
相关资源
最近更新 更多