9

在 Windows PowerShell 脚本中,我想执行将管道转换为 CSV 格式的代码,并且编码应该是 UTF-8。我怎样才能做到这一点?

4

2 回答 2

24

将此添加到管道的末尾:

| Export-Csv -Encoding UTF8

就是这么简单。

-Encoding参数可用于任何输出到文件的 cmdlet - Out-FileSet-ContentAdd-ContentExport-Clixml,可能还有一些我没有想到的其他 cmdlet。需要注意的一个问题是,对于 UTF16,您需要指定Unicode而不是UTF16(我认为后者更有意义,并且至少应该作为同义词提供,但显然微软没有)。完整的选项列表是:

Unicode,UTF7,UTF8,ASCII,UTF32,BigEndianUnicode,Default,OEM

几点注意事项:

  • ASCII从技术上讲,它不会为您提供 ASCII 编码,而是为您提供 Windows 代码页 1252(它基于扩展的 ASCII,通常非正式地称为 ASCII)。
  • Default为您提供其他选项中的任何一个是系统默认值。您可以使用[System.Text.Encoding]::Default.
于 2014-01-20T16:36:13.890 回答
0
Invoke-Sqlcmd -ServerInstance localhost -Database "$database" -Query "$qry"  -username "$username" -password "$password" | convertto-CSV -notype | out-file -encoding UTF8 -filepath $filename

这适用于 Powershell 2,并且在 convertto-CSV 不允许 -encoding 参数的情况下(而 outfile 允许)

于 2017-08-29T12:30:38.267 回答