gpt4 book ai didi

powershell - 如何最初使用 PowerShell 向 CSV 文件添加 header

转载 作者:行者123 更新时间:2023-12-03 00:59:05 25 4
gpt4 key购买 nike

我想首先向 CSV 文件添加标题。我最初想添加标题的原因是对于某些行,某些列值可能为空。

根据 Microsoft 文档,导出 csv 仅采用第一行中存在的标题/列。

When you submit multiple objects to Export-CSV, Export-CSV organizes the file >based on the properties of the first object that you submit. If the remaining >objects do not have one of the specified properties, the property value of >that object is null, as represented by two consecutive commas. If the >remaining objects have additional properties, those property values are not >included in the file.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-csv?view=powershell-6#notes

到目前为止我已经尝试过:

$csvContents =@()

foreach ($item in $items) {
$row = New-Object System.Object # Create an object to append to the array
$row | Add-Member -MemberType NoteProperty -Name "header1" -Value "value1"
$row | Add-Member -MemberType NoteProperty -Name "header2" -Value "value2"
$row | Add-Member -MemberType NoteProperty -Name "header3" -Value "value3"
$csvContents += $row # append the new data to the array
}

$csvContents | Export-CSV -NoTypeInformation -Path $ResultCsvPath

问题是,例如 Item1 可能只有 header1 和 header3,意味着这些列是动态的。因此导出后,结果 csv 将仅包含 header1 和 header3,而 header2 将丢失。

我期望的是我想最初添加 header1、header2、header3。

最佳答案

对于大型集合,这可能会花费一些时间,但以下内容可能对您有用:

假设这是您的收藏

$obj = @(
[pscustomobject]@{
'header1' = 'value1'
'header3' = 'value3'
},
[pscustomobject]@{
'header1' = 'value1'
'header2' = 'value2'
},
[pscustomobject]@{
'header3' = 'value3'
},
[pscustomobject]@{
'header1' = 'value1'
'header2' = 'value2'
'header3' = 'value3'
}
)

然后您可以添加缺少的属性,例如:

# Try and find all headers by looping over all items.
# You could change this to loop up to a maximum number of items if you like.
# The headers will be captured in the order in which they are found.
$headers = $obj | ForEach-Object {($_.PSObject.Properties).Name} | Select-Object -Unique

# Find the missing headers in the first item of the collection
# and add those with value $null to it.
$headers | Where-Object { ($obj[0].PSObject.Properties).Name -notcontains $_ } | ForEach-Object {
$obj[0] | Add-Member -MemberType NoteProperty -Name $_ -Value $null
}

# output on console
$obj

# output to csv file
$obj | Export-Csv -Path 'D:\test.csv' -NoTypeInformation

输出:

header1 header3 header2
------- ------- -------
value1 value3
value1 value2
value3
value1 value3 value2

关于powershell - 如何最初使用 PowerShell 向 CSV 文件添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58645411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com