Search code examples
powershellfile-iopowershell-3.0

How to combine the contents of multiple files in powershell


I was wondering how I would go about combining specific files together using powershell. Example: I want to take EDIDISC.UPD EDIACCA.UPD EDIBRUM.UPD ETC ETC ETC ETC and Combine the contents of these files together and make a new file named A075MMDDYY.UPD. Now I would want it to be able to be run by whomever has the .UPD files on their network drive. Such as example: Mine would be in N:\USERS\Kevin, someone else's may be in N:\USERS\JohnDoe.

So far I only have:

Param (
  $path = (Get-Location).Path,
  $filetype = "*.UPD",
  $files = (Get-ChildItem -Filter $filetype),
  $Newfile = $path + "\Newfile.UPD"
)
$files | foreach { Get-Content $_ | Out-File -Append $Newfile -Encoding ascii }

Solution

  • Focusing just on the aspect of concatenating (catting) the contents of multiple files to form a new file, assuming the current directory (.):

    $dir = '.'
    $newfile ="$dir/Newfile.UPD"
    Get-Content "$dir/*.UPD" -Exclude (Split-Path -Leaf $newFile) | 
      Out-File -Append -Encoding Ascii $newFile
    
    • You can pass a wildcard expression directly to Get-Content's (implied) -Path parameter in order to retrieve the contents of all matching files.

    • Since the output file is placed in the same dir. and matches the wildcard expression too, however, it must be excluded from matching, by filename, hence the -Exclude (Split-Path -Leaf $newFile) argument (this additionally assumes that there's no input file whose name is the same as the output file's).