简体   繁体   中英

Using Get-ChildItem with Get-Content

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

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

you can create an object too

Get-ChildItem -Recurse *.txt | %{ 
    New-Object psobject -Property @{
    Name=$_.Name 
    DirectoryName=$_.DirectoryName
    Length=$_.Length
    FirstLine= Get-Content $_ -First 1
    Numberline=(gc $_).Count
    }

  } | Export-Csv -Path 'C:\test.csv' -NoTypeInformation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM