最近看到有人问起一个问题,关于Powershell输出CSV格式后显示了乱码,脚本代码大体如下:
Get-Process | Format-Table -AutoSize ProcessName,PM,NPM | Export-Csv D:/process.csv
为什么我们在使用Format-Table定义表格样式输出后通过管道传递给Export-Csv这个cmdlet会导致产生乱码呢?打开process.csv文件后乱码如下:
#TYPE Microsoft.PowerShell.Commands.Internal.Format.FormatStartData ClassId2e4f51ef21dd47e99d3c952918aff9cd pageHeaderEntry pageFooterEntry autosizeInfo shapeInfo groupingEntry 033ecb2bc07a4d43b5ef94ed5a35d280 Microsoft.PowerShell.Commands.Internal.Format.AutosizeInfo Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo 9e210fe47d09416682b841769c78b8a3 27c87ef9bbda4f709f6b4002fa4af63c 27c87ef9bbda4f709f6b4002fa4af63c 27c87ef9bbda4f709f6b4002fa4af63c 27c87ef9bbda4f709f6b4002fa4af63c 27c87ef9bbda4f709f6b4002fa4af63c 27c87ef9bbda4f709f6b4002fa4af63c 27c87ef9bbda4f709f6b4002fa4af63c
我们通过分解脚本代码行看看到底是为什么?
Get-Process | Format-Table -AutoSize ProcessName,PM,NPM | Get-Member –MemberType Property
TypeName: Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Name MemberType Definition ---- ---------- ---------- autosizeInfo Property Microsoft.PowerShell.Comm... ClassId2e4f51ef21dd47e99d3c952918aff9cd Property System.String ClassId2e4f... groupingEntry Property Microsoft.PowerShell.Comm... pageFooterEntry Property Microsoft.PowerShell.Comm... pageHeaderEntry Property Microsoft.PowerShell.Comm... shapeInfo Property Microsoft.PowerShell.Comm... TypeName: Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Name MemberType Definition ---- ---------- ---------- ClassId2e4f51ef21dd47e99d3c952918aff9cd Property System.String ClassId2e4f... groupingEntry Property Microsoft.PowerShell.Comm... shapeInfo Property Microsoft.PowerShell.Comm... TypeName: Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Name MemberType Definition ---- ---------- ---------- ClassId2e4f51ef21dd47e99d3c952918aff9cd Property System.String ClassId2e4f... formatEntryInfo Property Microsoft.PowerShell.Comm... outOfBand Property System.Boolean outOfBand ... writeErrorStream Property System.Boolean writeError... TypeName: Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Name MemberType Definition ---- ---------- ---------- ClassId2e4f51ef21dd47e99d3c952918aff9cd Property System.String ClassId2e4f... groupingEntry Property Microsoft.PowerShell.Comm... TypeName: Microsoft.PowerShell.Commands.Internal.Format.FormatEndData Name MemberType Definition ---- ---------- ---------- ClassId2e4f51ef21dd47e99d3c952918aff9cd Property System.String ClassId2e4f... groupingEntry Property Microsoft.PowerShell.Comm...
我们会发现Format-Table是一种格式转换的格式指令对象流,所以当你再次通过Export-Csv输出的时候就会造成格式上的混乱产生乱码。
最后我去查阅了下网上的资料发现,同样只适合独立运行的还有,Out-Host, Out-File, Out-String, Out-Printer命令。