将文件名和上次写入时间附加为 CSV 中的列

Appending file name and last write time as columns in a CSV

我有一堆文本文件正在转换为 CSV。 例如我有几百个类似这样的 txt 文件

Serial Number : 123456
Measurement : 5
Test Data : 125

每个文件都被转换为 CSV 文件中的一行。我不知道如何为文件名和上次写入时间添加一个额外的列。

这就是我目前拥有的,可以将所有数据从 txt 复制到 CSV

$files = "path"
function Get-Data {
    param (
        [Parameter (Mandatory, ValueFromPipeline, Position=0)] $filename
    )


    $data=@{}
    $lines=Get-Content -LiteralPath $filename | Where-Object {$_ -notlike '*---*'}
    foreach ($line in $lines) {
            $splitLine=$line.split(":")
            $data.Add($splitLine[0],$splitLine[1])
            
             
       
    }
    return [PSCustomObject]$data
    
}
$files | Foreach-Object -Process {Get-Data $_} | Export-Csv -Path C:\Scripts\data.csv -NoTypeInformation -Force

我试过这样做,但没有任何效果。我可能试图以错误的方式添加数据。

$files = "path"
function Get-Data {
    param (
        [Parameter (Mandatory, ValueFromPipeline, Position=0)] $filename
    )


    $data=@{}
    $name = Get-ChildItem -literalpath $filename | Select Name
    $data.Add("Filename", $name)
    $lines=Get-Content -LiteralPath $filename | Where-Object {$_ -notlike '*---*'}
    foreach ($line in $lines) {
            $splitLine=$line.split(":")
            $data.Add($splitLine[0],$splitLine[1])
            
             
       
    }
    return [PSCustomObject]$data
    
}
$files | Foreach-Object -Process {Get-Data $_} | Export-Csv -Path E:\Scripts\Pico2.csv -NoTypeInformation -Force

这是您的代码的简化版本,应该可以按预期工作:

function Get-Data {
  param (
    [Parameter (Mandatory, ValueFromPipeline)] 
    [System.IO.FileInfo] $file # Accept direct output from Get-ChildItem 
  )

  process { # Process each pipeline input object

    # Initialize an ordered hashtable with 
    # the input file's name and its last write time.
    $data = [ordered] @{
      FileName = $file.Name
      LastWriteTime = $file.LastWriteTime
    }

    # Read the file and parse its lines
    # into property name-value pairs to add to the hashtable.
    $lines = (Get-Content -ReadCount 0 -LiteralPath $file.FullName) -notlike '*---*'
    foreach ($line in $lines) {
      $name, $value = ($line -split ':', 2).Trim()
      $data.Add($name, $value)
    }

    # Convert the hashtable to a [pscustomobject] instance
    # and output it.
    [PSCustomObject] $data

  }

}

# Determine the input files via Get-ChildItem and
# pipe them directly to Get-Data, which in turn pipes to Export-Csv.
Get-ChildItem "path" | 
  Get-Data |
    Export-Csv -Path C:\Scripts\data.csv -NoTypeInformation -Force