Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast and simple binary concatenate files in Powershell

Tags:

powershell

What's the best way of concatenating binary files using Powershell? I'd prefer a one-liner that simple to remember and fast to execute.

The best I've come up with is:

gc -Encoding Byte -Path ".\File1.bin",".\File2.bin" | sc -Encoding Byte new.bin 

This seems to work ok, but is terribly slow with large files.

like image 385
FkYkko Avatar asked Nov 23 '09 14:11

FkYkko


People also ask

How do I combine two binary files?

To combine binary files in Power Query Editor, select Content (the first column label) and select Home > Combine Files. Or you can just select the Combine Files icon next to Content.

How do I concatenate files in PowerShell?

Use Out-File to Concatenate Files Using PowerShell The Out-File cmdlet sends the output to a file. If the file does not exist, it creates a new file in the specified path. To concatenate files with Out-File , you will need to use the Get-Content cmdlet to get the content of a file.

How do I merge two binary files in Windows?

In the file tools manu you have the option of concatenating bin files. Add them and then type the name of the resulting file. Execution is instantaneous.

How do I concatenate strings in PowerShell?

In PowerShell, string concatenation is primarily achieved by using the “+” operator. There are also other ways like enclosing the strings inside double quotes, using a join operator, or using the -f operator. $str1="My name is vignesh."


2 Answers

The approach you're taking is the way I would do it in PowerShell. However you should use the -ReadCount parameter to improve perf. You can also take advantage of positional parameters to shorten this even further:

gc File1.bin,File2.bin -Encoding Byte -Read 512 | sc new.bin -Encoding Byte 

Editor's note: In the cross-platform PowerShell (Core) edition (version 6 and up), -AsByteStream must now be used instead of -Encoding Byte; also, the sc alias for the Set-Content cmdlet has been removed.

Regarding the use of the -ReadCount parameter, I did a blog post on this a while ago that folks might find useful - Optimizing Performance of Get Content for Large Files.

like image 154
Keith Hill Avatar answered Oct 03 '22 04:10

Keith Hill


It's not Powershell, but if you have Powershell you also have the command prompt:

copy /b 1.bin+2.bin 3.bin 

As Keith Hill pointed out, if you really need to run it from inside Powershell, you can use:

cmd /c copy /b 1.bin+2.bin 3.bin  
like image 34
João Angelo Avatar answered Oct 03 '22 05:10

João Angelo