Home > Back-end >  Powershell Loop Through Directory of Text Files and Append Filename Last Line in new Text File
Powershell Loop Through Directory of Text Files and Append Filename Last Line in new Text File

Time:12-06

I am wanting to iterate over a directory full of various text files, which have lines of content such as the below example:

Mark.Stevens;Wed 03/11/2020; 8:02:23.83

Paul.Robinson;Wed 03/11/2020; 9:52:24.78

And Filenames such as 'CII1234567.txt'.

And pull the filename along with the last line from the files themselves.

Currently I have the below code:

$textfiles = (Get-ChildItem C:\Users\KP\Downloads\Test\Workstations | Where-Object {$_.Extension -eq '.txt'}).FullName

ForEach ($textfile in $textfiles) {

Get-content $textfile -Tail 1 >> C:\Users\KP\Downloads\Test\Output.txt

Get-content $textfile.Basename >> C:\Users\KP\Downloads\Test\Output.txt

}

When I run the Powershell script it successfully grabs the content of each of the files such as:

Mark.Stevens;Wed 03/11/2020; 8:02:23.83

Paul.Robinson;Wed 03/11/2020; 9:52:24.78

However I have been having difficulty with successfully pulling the filename as well.

Ideally the resulting text file would look something like the below example:

CII1234567.txt Mark.Stevens;Wed 03/11/2020; 8:02:23.83

CII1234567.txt Paul.Robinson;Wed 03/11/2020; 9:52:24.78

Would anyone be able to help advise on how I can get the desired output?

CodePudding user response:

I think it is better you debug the code yourself. I like writing code that is simple to debug. When you try to put everything into one instruction you can't debug. You can always use foreach in powershell to debug. After you get code working you can combine statements if that is your style. I like using Format-Table for debugging because it is great for enumerating through powershell object.

$children = Get-ChildItem C:\Users\KP\Downloads\Test\Workstations | Where-Object {$_.Extension -eq '.txt'}
foreach($child in $children)
{
   $child | Format-Table
   foreach($textfile in $child)
   {
      $textfile | Format-Table
      foreach($row in $textfile)
      {
          "$textfile;"   $_  >> C:\Users\KP\Downloads\Test\Output.txt
      }
      
   }

}
  • Related