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

Python调用PowerShell遇希伯来字符编解码错误求助

解决Python调用PowerShell执行AD查询时的UnicodeDecodeError问题

问题根源

报错是因为PowerShell默认使用系统OEM编码(此处为cp1255)输出结果,该编码无法覆盖所有特殊字符/希伯来字符,而Python用text=True时会自动采用系统默认编码解码,导致出现UnicodeDecodeError。

解决方案

提供两种可靠的修复方式:

方法1:临时切换PowerShell编码为UTF-8,同时指定Python解码编码

修改subprocess调用,先让PowerShell切换到UTF-8编码输出,再指定Python用UTF-8解码结果:

import subprocess
username = input('Please enter user name: ')
# 先切换控制台编码为UTF-8(屏蔽切换提示),再执行AD查询命令
command = f'chcp 65001 >nul; Get-ADPrincipalGroupMembership -Identity {username} | select name, GroupCategory, GroupScope'
# 指定encoding='utf-8'确保解码正确
result = subprocess.run(['powershell.exe', '-Command', command], capture_output=True, text=True, encoding='utf-8')
r = result.stdout
print(r)

方法2:让PowerShell直接输出UTF-8字节流,Python手动解码

通过Out-String命令让PowerShell以UTF-8格式输出结果,Python捕获字节后自行解码:

import subprocess
username = input('Please enter user name: ')
# 用Out-String指定输出编码为UTF-8
command = f'Get-ADPrincipalGroupMembership -Identity {username} | select name, GroupCategory, GroupScope | Out-String -Encoding utf8'
result = subprocess.run(['powershell.exe', '-Command', command], capture_output=True)
# 手动用UTF-8解码字节流
r = result.stdout.decode('utf-8')
print(r)

说明

两种方法都通过UTF-8编码兼容所有Unicode字符(包括希伯来字符),避免了系统默认编码的局限性。方法1更通用,适合大多数PowerShell命令调用场景;方法2直接针对输出内容指定编码,精度更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 17:43:23