Last active
April 12, 2024 10:42
-
-
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 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 | |
# | |
## | |
$base64ext = ".b64" | |
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 -Encoding Byte | |
} | |
else | |
{ | |
$contentBytes = Get-Content $filePath -Encoding Byte | |
$base64 = [Convert]::ToBase64String($contentBytes) | |
Set-Clipboard -Value ($base64).ToString() | |
Set-Content -Path ("{0}{1}" -f $filePath,$base64ext) -Value $base64 | |
} |
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).
thanks a lot
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also copies the base-64 contents to the clipboard when converting to a base-64 file.