Python调用PowerShell传星号(*)触发Unicode解码错误怎么解决?
解决Python subprocess调用PowerShell时星号参数触发的Unicode解码错误
首先明确:参数中的*本身是PowerShell合法的通配符,不需要额外转义,你遇到的报错本质是编码不匹配问题,和星号传递没有直接关联:subprocess.check_output默认捕获PowerShell输出的字节流时,Windows环境下PowerShell默认输出编码为系统区域对应的ANSI编码(而非UTF-8),强制指定encoding=utf-8就会出现无法解码非法字节的报错。
已验证的最简解决方案
直接将subprocess.check_output替换为subprocess.getoutput即可,该方法会自动适配系统默认编码处理命令输出,星号参数也可以正常被PowerShell识别,修正后代码如下:
powershell_call = json.loads(subprocess.getoutput( f'powershell.exe {cmdlet_name} -Identity "{identity}" -Server {server} -Properties * | ConvertTo-Json -Depth {jsonDepth}' ))
其他可选解决方案
如果你不想使用subprocess.getoutput,也可以通过以下两种方式解决:
- 显式指定PowerShell输出编码为UTF-8,在命令开头插入编码配置语句:
powershell_cmd = f'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; {cmdlet_name} -Identity "{identity}" -Server {server} -Properties * | ConvertTo-Json -Depth {jsonDepth}' powershell_call = json.loads(subprocess.check_output(['powershell.exe', powershell_cmd], encoding='utf-8'))
- 拿到字节流后使用Windows系统默认ANSI编码解码:
output_bytes = subprocess.check_output([ 'powershell.exe', f'{cmdlet_name} -Identity "{identity}" -Server {server} -Properties * | ConvertTo-Json -Depth {jsonDepth}' ]) powershell_call = json.loads(output_bytes.decode('mbcs'))
内容的提问来源于stack exchange,提问作者Patryk Gołębiowski
相关产品推荐
相关产品推荐

