Amittai Shapira
Amittai Shapira

Reputation: 3827

Combine text from multiple files into a single file

I'm trying to create a text file that contains the content of my source code files concatenated. I've came up with the following concise code:

Get-ChildItem  -Recurse MySourcePath -Include "*.htm", "*.cs" | Foreach-Object 
{Get-Content $_.FullName | Add-Content MyFile.txt}

The problem is, after multiple files (hundreds or thousands), I'm starting to get the following error:

Add-Content : The process cannot access the file 'MyFile.txt' because it is being used by another process.

It seems like concurrency issue and I thought it was related to the pipelining mechanism, but using foreach didn't solve the problem.

What is the right way in PowerShell to protect my file from multiple writes? Is there a way to still utilize the pipeline?

Upvotes: 0

Views: 5468

Answers (3)

Randy
Randy

Reputation: 11

I know this is an old thread, but I found the following: https://blogs.msdn.microsoft.com/rob/2012/11/21/combining-files-in-powershell/

The line that actually combines the contents of all htm files into a single MyFile.txt, looks something like this:

Get-ChildItem -recurse -include "*.htm" | % { Get-Content $_ -ReadCount 0 | Add-Content MyFile.txt }

Upvotes: 0

Esperento57
Esperento57

Reputation: 17462

As explained here, your problem is add-content, just do it

Get-ChildItem $MySourcePath -Recurse -Include "*.htm", "*.cs" | get-content |  Out-File -Append MyFile.txt



#short version
gci -file $MySourcePath -Recurse -Include "*.htm", "*.cs" | gc >>  MyFile2.txt

Upvotes: 1

henrycarteruk
henrycarteruk

Reputation: 13207

You can pipe Get-ChildItem to Out-File to combine the files, it's only a single write operation then:

Get-ChildItem MySourcePath -Include "*.htm", "*.cs" -Recurse | Out-File MyFile.txt

Upvotes: 0

Related Questions