将Get-ChildItem与Get-Content一起使用

时间:2016-11-16 12:53:48

标签: powershell csv

我正在尝试列出文件属性和文件中第一行的内容。

命令:

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

给出了每个目录中文件的名称,目录名称和长度。

我还需要第一行的内容以及每个* .txt文件的行数。最后,所有信息都应该在一个CSV文件中。我怎么能这样做?

示例:

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

2 个答案:

答案 0 :(得分:2)

使用calculated propertiesfirst linenumber of lines属性添加到当前对象,并将结果通过管道传输到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

答案 1 :(得分:0)

你也可以创建一个对象

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
相关问题