Set Windows PowerShell to UTF-8 Encoding to Fix GBK Codec Can Not Encode Character Error – PowerShell Tutorial

By | May 20, 2020

The default encoding of powershell is not utf-8, when you are running python code using it, you may get gbk  codec cannot encode character error.

windows powershell gbk codec can not encode character error

To fix this error, we should make powershell support utf-8 encoding. In this tutorial, we will introduce you how to do.

There are two methods to set powershell to support utf-8 encoding, temporary and permanent. We will introduce them one by one.

Get powershell default encoding.

We can run code below in powershell to get the its default encoding.

[psobject].Assembly.GetTypes() | Where-Object { $_.Name -eq 'ClrFacade'} |
  ForEach-Object {
    $_.GetMethod('GetDefaultEncoding', [System.Reflection.BindingFlags]'nonpublic,static').Invoke($null, @())
  }

Then you will get this result.

get powershell default encoding

As to us, the default encoding of powershell is gb2312.

Set powershell encoding to utf-8 temporarily

You can run code below in powershell to make powershell encoding to utf-8.

PS C:\> $OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8
PS C:\> $PSDefaultParameterValues['*:Encoding'] = 'utf8'

Then you will find you current powershell terminal can output utf-8 characters.

However, if you open a new powershell terminal, you will find powershell will not support utf-8 again.

Set powershell encoding to utf-8 permanently

You can do as follow steps.

1.[home]+R and input control command.

open windows control panel command - control

2.Select “Clock, Language and Region”

select windows control panel - Clock, Language and Region

3.Select Region

select windows control panel - Region

4.Set utf-8

select use unicode utf-8

Restart your compter.

Then you can find your powershell can support utf-8 encoding.

For example: we will output a utf-8 text file.

windows powershell can support utf-8 encoding

You will find powershell can support utf-8 encoding.

Leave a Reply