Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

How to use additional character encodings in PowerShell Core (Linux) and Desktop (Windows)

Problem

You have to call [System.Text.Encoding]::RegisterProvider([System.Text.CodePagesEncodingProvider]::Instance) when you want to use additional character encodings in PowerShell Core (Linux). On the other hand, calling [System.Text.Encoding]::RegisterProvider([System.Text.CodePagesEncodingProvider]::Instance) causes RuntimeException.

PS > [System.Text.Encoding]::RegisterProvider([System.Text.CodePagesEncodingProvider]::Instance)
Unable to find type [System.Text.CodePagesEncodingProvider].
At line:1 char:42
+ ... ng]::RegisterProvider([System.Text.CodePagesEncodingProvider]::Instan ...
+                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Text.CodePagesEncodingProvider:TypeName) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

Solution

$PSVersionTable.PSEdition shows current PowerShell edition, so you can switch call [System.Text.Encoding]::RegisterProvider([System.Text.CodePagesEncodingProvider]::Instance) or not.

if ($PSVersionTable.PSEdition -eq "Core") {
  [System.Text.Encoding]::RegisterProvider([System.Text.CodePagesEncodingProvider]::Instance)
}