Handling Base64 encoded strings with PowerShell

I don’t handle Base64 strings very often – when I do I find myself searching for instructions every time. So I finally decided to add two small helper functions to my PowerShell profile.

function ConvertFrom-Base64String ([String]$InputString, [System.Text.Encoding]$Encoding) {
    $DecodedString = $Encoding.GetString([System.Convert]::FromBase64String($InputString))

function ConvertTo-Base64String ([String]$InputString, [System.Text.Encoding]$Encoding) {
    $StringBytes = $Encoding.GetBytes($InputString)
    $EncodedString = [System.Convert]::ToBase64String($StringBytes)

You can quickly edit your PowerShell profile file by typing <code data-enlighter-language="powershell" class="EnlighterJSRAW">code $PROFILE into your PowerShell window – this will pop up VS Code with your profile ready to edit.

Close/Reopen PowerShell or your PowerShell session in Windows Terminal and you can use these functions like so:

$Encoding = [System.Text.Encoding]::UTF8
$DecodedString = ConvertFrom-Base64String -InputString $String -Encoding $Encoding
$EncodedString = ConvertTo-Base64String -InputString  $String -Encoding $Encoding

You’ll need to know the encoding of the text if you’re using a Base64 string from somewhere else. A good default to try is [Encoding]::UTF8

Leave a comment