0

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?

Amittai Shapira
  • 3,749
  • 1
  • 30
  • 54

3 Answers3

1

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
Community
  • 1
  • 1
Esperento57
  • 16,521
  • 3
  • 39
  • 45
0

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
henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
  • I've tried that but it just creates a text file with all file names. I need all files content (i.e. the source code) to be concatenated into single file. You also haven't answered my question regarding what is the issue with what I've initially tried... – Amittai Shapira Apr 08 '17 at 01:16
0

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 }
Studocwho
  • 2,404
  • 3
  • 23
  • 29
Randy
  • 1
  • 2