SQLQuery
SQLQuery

Reputation: 11

Powershell - Extract first line from CSV files and export the results

Thanks in advance for the help.

I have a folder with multiple CSV files. I’d like to be able to extract the first line of each of the files and store the results in a separate CSV file. The newly created CSV file will have the first column as the file name and the second column to be the first line of the file. The output should look something like this (as an exported CSV File):

FileName,FirstLine
FileName1,Col1,Col2,Col3
FileName2,Col1,Col2,Col3

Notes:
There are other files that should be ignored. I’d like the code to loop through all CSV files which match the name pattern. I’m able to locate the files using the below code:

$targetDir ="C:\CSV_Testing\"
Get-ChildItem -Path $targetDir -Recurse -Filter "em*"

I’m also able to read the first line of one file with the below code:

Get-Content C: \CSV_Testing\testing.csv | Select -First 1

I guess I just need someone to help with looping through the files and exporting the results. Is anyone able to assist? Thanks

Upvotes: 1

Views: 238

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 59822

You basically need a loop, to enumerate each file, for this you can use ForEach-Object, then to construct the output you need to instantiate new objects, for that [pscustomobject] is the easiest choice, then Export-Csv will convert those objects into CSV.

$targetDir = "C:\CSV_Testing"
Get-ChildItem -Path $targetDir -Recurse -Filter "em*.csv" | ForEach-Object {
    [pscustomobject]@{
        FileName  = $_.Name
        FirstLine = $_ | Get-Content -TotalCount 1
    }
} | Export-Csv path\to\theResult.csv -NoTypeInformation

I have assumed the files actually have the .Csv extension hence changed your filter to -Filter "em*.csv", if that's not the case you could use the filter as you currently have it.

Upvotes: 1

Related Questions