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 | |
| } |
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
Powershell Core no longer knows about the
Byteencoding .->
Set-Content -Path $newFileName -Value $binary -AsByteStream