Combining multiple binary files into a single file using Powershell

Viewed 85

I have an existing Batch script that I need to rewrite as a Powershell script. However, it contains the following command that doesn't seem to have a Powershell equivalent.

copy *.0* /b output.bin

Is there a simpler way to do this than 'manually' iterating over each block of data in every file using [IO.File]::OpenRead() and appending it to the output?

Note that executing the copy command using cmd /c is not an option.

1 Answers

You can use a chunked approach via the -AsByteStream (PowerShell (Core) 7+) / -Encoding Byte (Windows PowerShell) parameter of the Get-Content and Set-Content cmdlets:

# Read the raw bytes in 64MB chunks across all matching input files
# and save to a single output file.
# Note: In Windows PowerShell, replace -AsByteStream with -Encoding Byte
Get-Content -ReadCount 64mb -AsByteStream *.0* |
  Set-Content -AsByteStream output.bin

Note:

  • Increase the chunk size passed to -ReadCount to speed up the operation, memory permitting (64mb is just a sample value).

    • If you're confident that the bytes making up the largest among the input files fit into memory as a whole (as a [byte[]] array), you can use -Raw instead of -ReadCount $n for the best performance.
  • Without -ReadCount, the bytes stream one by one, which is very slow.

Related