Foreach File in Files extract last line in file

Welcome Forums General PowerShell Q&A Foreach File in Files extract last line in file

This topic contains 4 replies, has 2 voices, and was last updated by

 
Participant
2 months ago.

  • Author
    Posts
  • #166364

    Participant
    Topics: 2
    Replies: 3
    Points: 28
    Rank: Member

    Hello Partners,

    Need to go through a list of files and save the last line of each file in another file

     all my attempts failed

    TRY 1

     foreach ($file in Get-ChildItem "C:\Users\Marcos\Documents\Adobe\" -Tail 1 ) { $file+ $file.fullname }
    
    

    TRY 2

    
    foreach ($file in Get-ChildItem "C:\Users\Marcos\Documents\Adobe\") {
    if ($arquivo -eq true) {
    Get-Content -Tail 1
    $file + $file.fullname }
    
    
  • #166396

    Participant
    Topics: 1
    Replies: 1528
    Points: 2,581
    Helping Hand
    Rank: Community Hero

    Almost ... 😉 ... try this:

    $ListOfLastLines = Get-ChildItem -Path 'C:\Users\Marcos\Documents\Adobe\'  -File |
        ForEach-Object {
            Get-Content -Path $_.FullName -Tail 1 
        }
    $ListOfLastLines | Out-File -FilePath 'C:\Users\Marcos\Documents\Result.txt'
  • #166447

    Participant
    Topics: 2
    Replies: 3
    Points: 28
    Rank: Member

    bro, its , very well, thanks so much.

    I've been trying to learn how to work with powershell but I've had a lot of trouble

    Thank you for your help

  • #166456

    Participant
    Topics: 2
    Replies: 3
    Points: 28
    Rank: Member

    more one simply question ,

     

    How can I add the filename before the last line?

    I tried concatenating the variable + $ ListOfLastLines.FullName, but I returned some errors.

  • #166468

    Participant
    Topics: 1
    Replies: 1528
    Points: 2,581
    Helping Hand
    Rank: Community Hero

    The proper way would be to create a custom object and export it as CSV file ... like this:

    $ListOfLastLines = Get-ChildItem -Path 'C:\Users\Marcos\Documents\Adobe\' -File |
        ForEach-Object {
            [PSCustomObject]@{
                FileName = $_.FullName
                LastLine = Get-Content -Path $_.FullName -Tail 1 
            }
        }
    $ListOfLastLines | Export-Csv -Path 'C:\Users\Marcos\Documents\Result.csv' -NoTypeInformation

You must be logged in to reply to this topic.