循环ConvertFrom-Csv返回的对象

问题描述 投票:0回答:1

我有下面的代码,它根据我们传递给它的特定列来分割文件。我在将结果输出到 csv 文件时遇到问题。截至目前,我得到了 csv 格式的输出

公司:ABC

描述:DEF

地区:GHI

我需要行列格式

公司、描述、地区

ABC、DEF、GHI

代码:-

function fBreakFiles() {
    param(
        [String]$pDirectory,
        [String]$pFileNameString,
        [String]$pDateColumnName,
        [String]$pNewFileString,
        [String]$pLogFile,
        [String]$pDateFormat
    )


    Get-ChildItem $pDirectory -Force | Where-Object { $_.Name -ilike "$pFileNameString" } | ForEach-Object {
        $FilePath = $_.FullName
        Write-Output "################ $(Get-Date -Format 'yyyy/MM/dd hh:mm:ss:fff') :: Starting to extract source file at location $FilePath  `r`n" | Out-File $pLogFile -Append

        # Open the CSV file for reading
        $streamReader = [System.IO.StreamReader]::new($FilePath)

        # Get header line
        $header = $streamReader.ReadLine()

        # Set the buffer size based on your requirements
        $bufferSize = 2000
        $buffer = @()

        while ($streamReader.Peek() -ge 0) {
        # Read a block of lines into the buffer
        $buffer = 1..$bufferSize | ForEach-Object { $streamReader.ReadLine() }

        # Group the buffer data by required column
        $csvString = $buffer -join "`n"
        $csvObject = $csvString | ConvertFrom-Csv -Header ($header -split ',')
        $groupedData = $csvObject | Group-Object { $_.$pDateColumnName.Trim() }

        foreach ($group in $groupedData) {
            $DateString = ([datetime]::parseexact(($group.name), $pDateFormat, $null)).ToString("yyyy-MM-dd")
            $outputPath = Join-Path $pSourceDirectory "$pNewFileString$DateString.csv"
            if ($Date -ne $DateString)
            {
            $header | Out-File -Append -FilePath $outputPath
            }
            $Date = $DateString
            $group.Group | Out-File -Append -FilePath $outputPath
        }
    }
}
powershell
1个回答
0
投票

正如 @Mathias 提到的,在将对象写入文件之前,您需要将对象转换回 CSV 格式。

$group.Group | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File -Append -FilePath $outputPath

foreach ($group in $groupedData) {
    $DateString = ([datetime]::parseexact(($group.name), $pDateFormat, $null)).ToString("yyyy-MM-dd")
    $outputPath = Join-Path $pSourceDirectory "$pNewFileString$DateString.csv"
    if ($Date -ne $DateString)
    {
        $header | Out-File -Append -FilePath $outputPath
    }
    $Date = $DateString
    $group.Group | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File -Append -FilePath $outputPath
}
© www.soinside.com 2019 - 2024. All rights reserved.