Anthony Eggleston
Anthony Eggleston

Reputation: 21

Powershell convert a variable to utf-16

I am struggling to import a csv file making all content a variable then turn only one of the variables into utf-16. I have everything else just struggling to convert it in the following format:

Example needing to convert the word Hello World to 00480065006c006c006f00057006f0072006c0064.

The script would look similar to this.

$text = "Hello World"::UTF16

$text

Is this even possible? Or is there a way to convert it?

Upvotes: 1

Views: 3465

Answers (1)

Theo
Theo

Reputation: 61253

The output you desire is the hex representation of UTF-16 Big Endian encoding, known as BigEndianUnicode.

You can create a helper function that converts a string to that:

function ConvertTo-Utf16BE {
    [CmdletBinding()]
    Param (
        [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true)]
        [string]$String
    )
    $enc = [system.Text.Encoding]::BigEndianUnicode
    ($enc.GetBytes($string) | ForEach-Object {'{0:X2}' -f $_ }) -join ''
}

'Hello World' | ConvertTo-Utf16BE

Output:

00480065006C006C006F00200057006F0072006C0064

Upvotes: 5

Related Questions