Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Get-ChildItem with Get-Content

Tags:

powershell

csv

I’m trying to make a list of file properties and the content of the first line in the files.

The command:

get-ChildItem -Recurse *.txt | select-object Name, DirectoryName, Length

gives me the names, the directory names and the lengh of the files in each directory.

I need also the content of the first line as well as the number of lines of each *.txt-file. In the end all the information should be in one CSV-file. How can I do that?

Example:

File_01.txt, C:\folder, 243, Text of the first line of the File_01.txt, number of lines in File_01.txt
File_02.txt, C:\folder, 290, Text of the first line of the File_02.txt, number of lines in File_02.txt
File_03.txt, C:\folder, 256, Text of the first line of the File_03.txt, number of lines in File_03.txt
like image 488
RonLat Avatar asked Jan 29 '26 01:01

RonLat


1 Answers

Use calculated properties to add the first line and number of lines properties to the current object and pipe the result to the Export-Csv cmdlet:

Get-ChildItem -Recurse *.txt | 
    select-object Name, 
        DirectoryName, 
        Length, 
        @{l='first line'; e={$_ |Get-Content -First 1}}, 
        @{l='number of lines'; e={$_ | Get-Content | Measure-Object | select -ExpandProperty Count}} |
    Export-Csv -Path 'C:\test.csv' -NoTypeInformation
like image 124
Martin Brandl Avatar answered Jan 31 '26 20:01

Martin Brandl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!