Write Binary Files in PowerShell

Write Binary Files in PowerShell

Using Add-Content Cmdlet

Use the Add-Content cmdlet to write binary files in PowerShell.

This script created a new file named test.bin in the current working directory and wrote the binary data to the file. The script will append data to the existing file if the file already exists. First, we stored the array of bytes in $binaryData containing different values.

Then, we used the Add-Content cmdlet to write provided binary data to the specified .bin file; in our case, it is in the current directory. Here, the -Path parameter was used to specify the file path while the -Value parameter was used to specify the content to be added; in this case, it is the $binaryData variable. Next, the -Encoding Byte parameter tells PowerShell to write the data as a binary file.

Using the [IO.File]::WriteAllBytes() Method

Use [IO.File]::WriteAllBytes() method to write binary files in PowerShell.

Here, we used the [IO.File]::WriteAllBytes() method to write the content of the byte array ($binaryData) to a binary file. The first parameter was the file path; in this case, it is test.bin in the current directory; the second parameter was the byte array ($binaryData) that contains the binary data.

Until now, we have learned how to write a binary array to a binary file; let’s see how we can write the binary file when we are provided with the base64 encoded string.

Using FromBase64CharArray() with Add-Content

To write to a binary file in PowerShell:

  • Use the FromBase64CharArray() to convert the base64 encoded string to byte array.
  • Use the Add-Content cmdlet to write a byte array (received from the previous step) to a binary file.

In the above code fence, the $base64String variable contained a base64 encoded string; this string was the encoded version of a byte array. The $binaryData variable receives the result of the [System.Convert]::FromBase64String() method; this method converts the base64 encoded string to a byte array.

Then, we used the Add-Content cmdlet that we discussed in the first section to write the binary data stored in the $binaryData variable to a file named test.bin. Here, the -Encoding Byte parameter was used to inform PowerShell to write the specified data as a binary file.

Note: The base64 string should be a valid base64 encoded string, otherwise, the [System.Convert]::FromBase64String() method will throw an exception.

That’s all about how to write binary files in PowerShell.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *