UTF-8 output from PowerShell

后端 未结 4 1778
我在风中等你
我在风中等你 2020-11-28 23:12

I\'m trying to use Process.Start with redirected I/O to call PowerShell.exe with a string, and to get the output back, all in UTF-8. But I don\'t s

4条回答
  •  醉梦人生
    2020-11-28 23:56

    This is a bug in .NET. When PowerShell launches, it caches the output handle (Console.Out). The Encoding property of that text writer does not pick up the value StandardOutputEncoding property.

    When you change it from within PowerShell, the Encoding property of the cached output writer returns the cached value, so the output is still encoded with the default encoding.

    As a workaround, I would suggest not changing the encoding. It will be returned to you as a Unicode string, at which point you can manage the encoding yourself.

    Caching example:

    102 [C:\Users\leeholm]
    >> $r1 = [Console]::Out
    
    103 [C:\Users\leeholm]
    >> $r1
    
    Encoding                                          FormatProvider
    --------                                          --------------
    System.Text.SBCSCodePageEncoding                  en-US
    
    
    
    104 [C:\Users\leeholm]
    >> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
    
    105 [C:\Users\leeholm]
    >> $r1
    
    Encoding                                          FormatProvider
    --------                                          --------------
    System.Text.SBCSCodePageEncoding                  en-US
    

提交回复
热议问题