Marc Clar
Marc Clar

Reputation: 1

Powershell add file name to text file

I am currently writing a script that consolidates all of the contents of several text files into one file. I would like to (if possible), write into the file, the name of the file above the contents from that file.

Example:

Textfile1.txt

ContentContentContent
ContentContentContent

Textfile2.txt

ContentContentContent
ContentContentContent

Textfile3.txt

ContentContentContent
ContentContentContent

Is this possible?

Upvotes: 0

Views: 4995

Answers (1)

FoxDeploy
FoxDeploy

Reputation: 13537

Yep, it's not too hard at all. We get a listing of the files we want using the Dir command, then we pipe that into ForEach to run a {scriptblock}. We'll then build a $variable to create the blob of text that we'll add to our existing file (Output.txt).

We can use the $_ variable to pull out the FileName property, and then use the Get-Content cmdlet to grab the text of the file, giving us the fields you wanted. We join them both with the `n NewLine character. The end result, is this:

dir *.txt | ForEach {
    $variable = "$($_.Name)`n$(Get-content $_.FullName)"
    Add-Content -Value $variable -Path .\Output.txt
}

Which gives us an output like this:

TextFile1.txt
ContentContentContent ContentContentContent
TextFile2.txt
ContentContentContent ContentContentContent
TextFile3.txt
ContentContentContent ContentContentContent

Upvotes: 2

Related Questions