PowerShell only accepts Base64 encodings of UTF-16 LE-encoded strings with its
-EncodedCommand
parameter.
UTF-16 LE is what Unicode
stands for in [System.Text.Encoding]::Unicode
, and it encodes the vast majority of Unicode characters (code points) as two bytes each; it is also the string encoding used internally by both VBScript and PowerShell.
By contrast, most VBScript solutions out there use the single-byte ASCII encoding, and even the otherwise laudably Unicode-aware https://www.base64encode.org/ only offers UTF-8-based encoding (which is a mostly-single-byte-for-Western-languages encoding with other languages' chars. represented as 2-4 bytes).
Here's a robust UTF-16 LE-based Base64 encoding solution.
I've posted a more modular variant that optionally supports UTF-8 here; the code in both locations builds on this great answer.
Example call:
Base64EncodeUtf16Le("(get-date).date") ' -> "KABnAGUAdAAtAGQAYQB0AGUAKQAuAGQAYQB0AGUA"
Source code:Tip of the hat to MC ND for helping to simplify the solution.
' Base64-encodes the specified string using UTF-16 LE as the underlying text
' encoding.
Function Base64EncodeUtf16Le(ByVal sText)
Dim bytesUtf16Le
' Create an aux. stream from which we can get a binary (byte array)
' representation of the input string in UTF-16 LE encoding.
With CreateObject("ADODB.Stream")
' Create a UTF 16-LE encoded text stream...
.Type = 2 ' adTypeText
.Charset = "utf-16le"
.Open
.WriteText sText
' ... and convert it to a binary stream,
' so we can get the string as a byte array
.Position = 0
.Type = 1 ' adTypeBinary
.Position = 2 ' Skip BOM
bytesUtf16Le = .Read
.Close
End With
' Use an aux. XML document with a Base64-encoded element.
' Assigning a byte stream (array) to .NodeTypedValue
' automatically performs Base64-encoding, whose result can then be accessed
' as the element's text.
With CreateObject("Msxml2.DOMDocument").CreateElement("aux")
.DataType = "bin.base64"
.NodeTypedValue = bytesUtf16Le
Base64EncodeUtf16Le = .Text
End With
End Function