Last active
November 17, 2020 17:56
-
-
Save philipmat/90937a7044be734d4811e44eaf19f61a to your computer and use it in GitHub Desktop.
ConvertTo-Base64 - Powershell script
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
<# | |
.SYNOPSIS | |
Converts a file to BASE64 encoding and displays the encoded content. | |
.PARAMETER InputFile | |
The file to be converted to Base64. Displays the encoded string to output (see -ToJson) | |
.PARAMETER ToJson | |
Instead of displaying the raw Base64, it outputs a JSON-formatted object. | |
.EXAMPLE | |
C:\PS>Convert-ToBase64 -InputFile test.txt | |
dGVzdA0K | |
.EXAMPLE | |
C:\PS>Convert-ToBase64 test.txt | |
dGVzdA0K | |
.EXAMPLE | |
C:\PS>Convert-ToBase64 -InputFile test.txt -ToJson | |
{"content":"dGVzdA0K"} | |
.EXAMPLE | |
C:\PS>Convert-ToBase64 -InputFile test.txt | Out-File -Encoding ascii c:\temp\test.txt.base64 | |
# => writes output to file | |
.EXAMPLE | |
C:\PS>Convert-ToBase64 test.txt -ToJson | Set-Clipboard | |
# => copies JSON to clipboard | |
#> | |
[CmdletBinding()] | |
Param( | |
[Parameter(Mandatory, Position = 0)] | |
[string]$InputFile, | |
[switch]$ToJson | |
) | |
if (-not (Test-Path -LiteralPath $InputFile)) { | |
Write-Warning "Couldn't find file: $InputFile" | |
exit 1 | |
} | |
$outputString = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($InputFile)) | |
if ($ToJson) { | |
Add-Type -AssemblyName System.Web.Extensions | |
# [System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") | |
$jsonSerializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer | |
$outputString = $jsonSerializer.Serialize(@{ content = $outputString }) | |
} | |
$outputString |
Reddit review and comments to incorporate: https://www.reddit.com/r/PowerShell/comments/800jnc/converttobase64_encodes_files_to_base64/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shorter version at: http://philipm.at/2018/base64_in_powershell.html