Base64 Encode and Decode a String in PowerShell

PowerShell has no Base64 cmdlet, but .NET does the job in one line each way. Turn the text into bytes, then the bytes into Base64:

PowerShell
$b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('Hello from PowerShell'))
$b64

And back again:

PowerShell
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b64))

Hello from PowerShell becomes SGVsbG8gZnJvbSBQb3dlclNoZWxs, and decoding gives the original text back.

Windows PowerShell 5.1: Hello from PowerShell encoded with ToBase64String gives SGVsbG8gZnJvbSBQb3dlclNoZWxs, and FromBase64String turns it back into Hello from PowerShell

Use the Same Encoding Both Ways

Base64 works on bytes, not text, so the encoding you pick changes the result. The same string encoded with [Text.Encoding]::Unicode (UTF-16) starts SABlAGwA instead of SGVsbG8g. Decode with a different encoding from the one used to encode and you get the wrong characters back. UTF8 is what most web APIs and config files expect.

Encode a Command for -EncodedCommand

powershell.exe -EncodedCommand and pwsh -EncodedCommand expect UTF-16, which .NET calls Unicode. This is handy when a command full of quotes has to pass through another tool:

PowerShell
$enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes("'encoded ok'"))
powershell.exe -NoProfile -EncodedCommand $enc

Encode a File

PowerShell
$path = (Resolve-Path .\logo.png).Path
$b64 = [Convert]::ToBase64String([IO.File]::ReadAllBytes($path))
[IO.File]::WriteAllBytes("$env:TEMP\logo-copy.png", [Convert]::FromBase64String($b64))

The .NET file methods do not follow cd in PowerShell, so give them a full path. That is what Resolve-Path is for. Pipe $b64 to Set-Clipboard to paste it somewhere else.

Windows PowerShell 5.1 and PowerShell 7

The [Convert] and [Text.Encoding] calls give the same results in both. The difference is when you save decoded text with Set-Content: 5.1 writes in the old ANSI code page by default and 7 writes UTF-8, so add -Encoding UTF8 in 5.1.

Base64 is not encryption. Anyone can decode it, so it is no place to hide a password.

Related

If SQL Server is part of your day job, my current work lives over at sqldba.blog: production DBA scripts, an error library and the SSMS guide.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *