具有UTF-8编码的Powershell字符串变量

问题描述 投票:1回答:1

我检查了许多与此相关的问题,但是找不到解决我问题的方法。基本上,我想将UTF-8编码的字符串存储到变量中,然后使用该字符串保存使用该字符串命名的文件。

例如,我正在尝试下载youtube视频。如果我们打印视频标题,则会显示非英语字符(ytd为youtube-dl):

./ytd https://www.youtube.com/watch?v=GWYndKw_zbw -e

输出:[LEEPLAY] 시티팝 입문 City Pop MIX (Playlist)

但是如果我将其存储在变量中并打印出来,则会忽略韩文字符:

$vtitle= ./ytd https://www.youtube.com/watch?v=GWYndKw_zbw -e

$vtitle

输出:[LEEPLAY] City Pop MIX (Playlist)

powershell windows-10 youtube-dl
1个回答
0
投票

当PowerShell解释外部程序的输出时(例如您的情况下为ytd它假定输出使用[Console]::OutputEncoding中反映的字符编码。

注意:

  • Interpreting

    是指PowerShell captures(例如$output = ...),relays(例如... | Select-String ...)或redirects(例如[ C0])外部程序的输出。
  • 相反,打印直接到显示器

  • 不受影响,因为不涉及PowerShell(这解释了为什么在console中看起来像预期的字符)。

    如果... > output.txt报告的编码与手头外部程序使用的编码不同,那么PowerShell misinterprets

输出。

要解决此问题,您必须(临时)设置[Console]::OutputEncoding以匹配外部程序使用的编码

例如,如果[Console]::OutputEncoding]输出UTF-8编码的文本:

ytd

重要

  • 修改$prev = [Console]::OutputEncoding [Console]::OutputEncoding = [Text.Encoding]::Utf8 $vtitle = ./ytd https://www.youtube.com/watch?v=GWYndKw_zbw -e $vitle [Console]::OutputEncoding = $prev 以匹配外部程序的字符编码在PowerShell Core

    中当前已损坏,自7.0.0-preview.4起-参见[Console]::OutputEncoding; Windows PowerShell不受影响。
  • [this GitHub bug report默认为

  • 反映与旧系统语言环境的OEM代码页相关的编码,如[Console]::OutputEncoding所报告(例如,在美式英语系统上为chcp)。
    • Windows 10的最新版本现在允许437(从Windows 10版本1903开始,该功能仍处于beta中),考虑到大多数现代命令行实用程序“说” UTF- 8
© www.soinside.com 2019 - 2024. All rights reserved.