-
-
Save jdmallen/82c4be9cf0f6c86cd8911a4af13848d9 to your computer and use it in GitHub Desktop.
| 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 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
Powershell Core no longer knows about the Byte encoding .
->
Set-Content -Path $newFileName -Value $binary -AsByteStream
@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!
Also copies the base-64 contents to the clipboard when converting to a base-64 file.