2016-11-16 34 views
3

我正在嘗試製作文件屬性列表和文件中第一行的內容。使用Get-ChildItem和Get-Content

命令:

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

給我的名,目錄名,並在每個目錄中的文件的lengh。

我還需要第一行的內容以及每個* .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

使用calculated properties的結果first 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 
+0

謝謝!這對我來說非常合適。 我試圖過濾文件的結果,其中包含字符串「Transaction Report」。 管道: '| | where-object {$ _ | select-string -pattern「Transaction Report」-eq $ true}' 因爲找不到匹配參數名稱「eq」的位置參數。我如何根據字符串模式來對這些文件進行歸檔? – Ron

+0

歡迎Ron。請考慮接受答案。另外,請開始一個新的問題 –

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 
相關問題