简体   繁体   English

将具有不同列的 PS object 的数组导出到 csv

[英]export array of PS object with different columns to csv

I have a little issue with an array exported.我对导出的数组有一点问题。 I have an array that contains objects with different fields (a total of 12 fields) and I can't export all the fields to CSV using Export-CSV and Out-File.我有一个包含具有不同字段(总共 12 个字段)的对象的数组,我无法使用 Export-CSV 和 Out-File 将所有字段导出到 CSV。

For the purpose of the example:出于示例的目的:

$logs = @()
$logs | export-csv -path c:\test.csv --NoTypeInformation

This is the contents of the array ($ Logs):这是数组的内容($ Logs):

$logs[0]
LogTime             : 2017-03-20 07:10:32.917
LogName             : Network connection detected (rule: NetworkConnect)
DeviceName          : K***M.w****l.local
ProcessGuid         : {297FCCB8-2783-58C8-0000-0010EB030000}
ProcessId           : 4
User                : NT AUTHORITY\SYSTEM
DestinationHostname : W***C
DestinationIp       : 10.**.***.6
DestinationIsIpv6   : false
DestinationPort     : 445
DestinationPortName : microsoft-ds
Image               : System
Initiated           : true
Protocol            : tcp
SourceHostname      : K**M.w***l.local
SourceIp            : 10.**.***.11
SourceIsIpv6        : false
SourcePort          : 53786

$logs[1]
LogTime           : 2017-03-20 11:14:05.553
LogName           : Process Create (rule: ProcessCreate)
DeviceName        : K***M.w***l.local
LogonId           : 0x1a84303
ParentCommandLine : C:\Windows\Explorer.EXE
ParentImage       : C:\Windows\explorer.exe
ParentProcessGuid : {297FCCB8-4358-58C9-0000-00103AB04800}
ParentProcessId   : 2884
ProcessGuid       : {297FCCB8-B97D-58CF-0000-00100D4EA801}
ProcessId         : 2440
TerminalSessionId : 2
User              : W***L\administrator
Image             : \\10.10.**0.6\share\Installs\AVG_Protection_Free_1606.exe
CommandLine       : "\\10.10.**0.6\share\Installs\AVG_Protection_Free_1606.exe" 
CurrentDirectory  : \\10.10.**0.6\share\Installs\
Hashes            : SHA1=E1CC52656F0AB86757E551C4181E4E11D6B2C811,MD5=8E1B5B613267120F1A6979021B0A1ED7,SHA256=6FE9ADD42C149CC4697124293A764B2CFD908F4A3CE6E88BAB35D5CF85620EC6,IMPHASH=D8843771C5D1046A951FECEB11DD00A8
IntegrityLevel    : High
LogonGuid         : {297FCCB8-B971-58CF-0000-00200343A801}

How can I export it to CSV so that columns are not missed?如何将其导出到 CSV 以便不会错过列?

Thanks!谢谢!

Export-Csv determines the columns from the property names of the first object passed, as noted in the documentation .文档中所述, Export-Csv根据传递的第一个 object 的属性名称确定列。 To circumvent this, you can use -Append -Force to write to an existing CSV file with all column headers already specified in it.为了避免这种情况,您可以使用-Append -Force写入现有的CSV 文件,其中已指定所有列标题。 You can add these manually, or to extract each unique property name from all objects in $logs , you can use something like:您可以手动添加这些,或者从$logs中的所有对象中提取每个唯一属性名称,您可以使用以下内容:

$OutColumns = $logs | ForEach-Object {$_.PSObject.Properties.Name} | Select-Object -Unique
$OutColumns -replace '"','""' -join '","' -replace '^|$','"' | Out-File C:\test.csv

If you're working with large amounts of data, the following may be a little faster:如果您正在处理大量数据,以下可能会更快一些:

$OutColumns = [System.Collections.Generic.List[string]]::new()
foreach ($obj in $logs) {
    foreach ($propName in $obj.PSObject.Properties.Name) {
        if ($OutColumns -notcontains $propName) {
            $OutColumns.Add($propName)
        }
    }
}
$OutColumns -replace '"','""' -join '","' -replace '^|$','"' | Out-File C:\test.csv

You can then append the $logs entries to this file with:然后,您可以使用 append 将$logs条目添加到此文件:

$logs | Export-Csv -Path C:\test.csv -NoTypeInformation -Append -Force

The -Force parameter is required with -Append here, else it will throw an error about mismatched property names. -Force参数是需要的-Append在这里,否则它会抛出一个关于不匹配的属性名称的错误。

Also note that when importing this again, every child object will have every property, but the missing ones will be empty strings .另请注意,再次导入时,每个子 object 将具有每个属性,但缺少的将是空字符串 For this reason, as mentioned in the comments, it may be better to separate objects with different property sets.出于这个原因,正如评论中提到的,最好将具有不同属性集的对象分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM