0

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?

1
  • Can you provide more details, preferably some sample code, showing how you are grabbing the list of file names and writing them out? The answer really depends on how you are currently doing things. Commented Mar 19, 2015 at 16:03

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Please note that dir is an alias for Get-ChildItem and ForEach is an alias for ForEach-Object. Clarification required if the OP wants single line or multiline input from the file contents.
Thank you so much for your help everyone, you answered my questions perfectly!
@MarcClar If this answered your question ( which it does not look like it completely since you made a new one) Please mark this as accepted. You should have just asked the answerer about your issue so he could have updated the answer here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.