Encode a string in UTF-8

75,335

Solution 1

Try this instead:

$enc = [System.Text.Encoding]::UTF8
$consumerkey ="xvz1evFS4wEEPTGEFPHBog"
$encconsumerkey= $enc.GetBytes($consumerkey)

Solution 2

If you just want to write the string to file:

$consumer_key ="xvz1evFS4wEEPTGEFPHBog"
$consumer_key |  Out-File c:\path\utf8file.txt -Encoding UTF8

Solution 3

Encode/Decode:

$enc = [System.Text.Encoding]::UTF8.GetBytes("â")
# 195 162
[System.Text.Encoding]::UTF8.GetString($enc)
# â
[System.Text.Encoding]::ASCII.GetString($enc)
# ??
[System.Text.Encoding]::Default.GetString($enc) # Windows-1252
# â

This is the best question I search that lead me to the above solution for text encoding/decoding characters in PowerShell. In my case I was trying to debug malformed UTF8 characters. Hope it helps someone in the future.

-Check that BOM

Share:
75,335
user3562182
Author by

user3562182

Updated on July 09, 2022

Comments

  • user3562182
    user3562182 almost 2 years

    I want to encode a string into UTF8 in PowerShell.

    This is what I tried:

    $consumer_key ="xvz1evFS4wEEPTGEFPHBog"
    $enc_consumer_key = System.Text.UTF8Encoding($consumer_key)
    

    But I get an error:

    System.Text.UTF8Encoding in not recognize as the name of cmdlet