Last active
April 24, 2025 21:15
-
-
Save jdmallen/82c4be9cf0f6c86cd8911a4af13848d9 to your computer and use it in GitHub Desktop.
Powershell script to convert a binary file to/from a base64 text file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Param( | |
| $filePath, | |
| [switch]$reverse = $false | |
| ) | |
| ## Usage | |
| # | |
| # From binary to UTF8 base-64 file with "b64" extension: | |
| # .\convert_binary_file_to_base64.ps1 path\to\file.bin | |
| # | |
| # From UTF8 base-64 file back to binary: | |
| # .\convert_binary_file_to_base64.ps1 -reverse path\to\file.bin.b64 | |
| # | |
| # Update (20241010): Add compatibility with PowerShell major versions >5, increase conversion speed with "-Raw" arg. | |
| ## | |
| $base64ext = ".b64" | |
| $encodingArg = if ([int](Get-Host).Version.Major -gt 5) {@{AsByteStream = $true}} else {@{Encoding = "Byte"}} | |
| if ($reverse) | |
| { | |
| $contentString = Get-Content $filePath -Encoding UTF8 | |
| $binary = [Convert]::FromBase64String($contentString) | |
| $originalFileName = ($filePath -split $base64ext)[0] | |
| $ext = [IO.Path]::GetExtension($originalFileName) | |
| $filenameWithoutExt = [IO.Path]::GetFileNameWithoutExtension($originalFileName) | |
| $parentDir = [IO.Path]::GetPathRoot($originalFileName) | |
| $unixTimeStamp = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() | |
| $newFileName = ("{0}{1}{2}{3}{4}" -f $parentDir, $filenameWithoutExt, ".", $unixTimeStamp , $ext) | |
| Set-Content -Path $newFileName -Value $binary @encodingArg | |
| } | |
| else | |
| { | |
| $contentBytes = Get-Content $filePath -Raw @encodingArg | |
| $base64 = [Convert]::ToBase64String($contentBytes) | |
| Set-Clipboard -Value ($base64).ToString() | |
| Set-Content -Path ("{0}{1}" -f $filePath, $base64ext) -Value $base64 | |
| } |
thanks a lot
Powershell Core no longer knows about the Byte encoding .
->
Set-Content -Path $newFileName -Value $binary -AsByteStream
Author
@janv8000 Updated; thanks for letting me know. Looks like only PowerShell Core 6.2.3 was out when I originally wrote it, and it definitely wasn't on my radar yet. 😅 Is now, though!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing the combination of encodings that makes this work without tacking on extra characters like it did when I tried.
I wrapped this in a function and added a line after 28 to print the generated file name to stdout so I can pipe that filename to another script. I'm guessing there's a more elegant 'idiomatic Powershell' way of doing that but I'm more familiar with Bash (where base64 encoding and decoding is commonly available and simple).