Export-Csv 等价于 Write-Output

Equivalent of Export-Csv to Write-Output

如何将对象转换为一系列 CSV 字符串并将字符串输出到另一个命令?

Export-Csv cmdlet 只会输出到一个文件。我想将 CSV 输出发送到另一个命令或脚本输出。

作为解决方法,我可以对文件使用 Export-Csv,读取文件,然后删除文件,但这种方法有太多不必要的开销。

Export-Csv

Converts objects into a series of comma-separated value (CSV) strings and saves the strings to a file.

如果要将对象转换为 CSV 并将结果return转换为标准输出而不是文件,则应使用 ConvertTo-CSV cmdlet。

The ConvertTo-CSV cmdlet returns a series of comma-separated value (CSV) strings that represent the objects that you submit. You can then use the ConvertFrom-Csv cmdlet to recreate objects from the CSV strings. The objects converted from CSV are string values of the original objects that contain property values and no methods.

您会发现大多数内置 Export- cmdlet 都有一个 ConvertTo- 等效项。另一个发现 cmdlet 的好方法是使用 Get-Command 和通配符:

~> Get-Command *csv

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           epcsv -> Export-Csv
Alias           ipcsv -> Import-Csv
Cmdlet          ConvertFrom-Csv                                    3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          ConvertTo-Csv                                      3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Export-Csv                                         3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Import-Csv                                         3.1.0.0    Microsoft.PowerShell.Utility

Export-csvConvertTo-CSV 的组合,通过管道传输到 Out-file :

例如:

Get-Process | Select-Object -property Name,ID,VM,PM | ConvertTo-CSV | Out-File test2.html

您可以使用:

$a = Get-Process | Select-Object -property Name,ID,VM,PM | ConvertTo-CSV