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

  • This topic has 4 replies, 2 voices, and was last updated 7 months ago by
    Participant
    .
Viewing 4 reply threads
  • Author
    Posts
    • #166364
      Participant
      Topics: 2
      Replies: 3
      Points: 29
      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: 2
      Replies: 1735
      Points: 3,545
      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: 29
      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: 29
      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: 2
      Replies: 1735
      Points: 3,545
      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
Viewing 4 reply threads
  • The topic ‘Foreach File in Files extract last line in file’ is closed to new replies.