Encode a string in UTF-8
Asked Answered
B

4

23

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

Bekah answered 23/4, 2014 at 23:15 Comment(0)
M
32

Try this instead:

$enc = [System.Text.Encoding]::UTF8
$consumerkey ="xvz1evFS4wEEPTGEFPHBog"
$encconsumerkey= $enc.GetBytes($consumerkey)
Maunder answered 24/4, 2014 at 0:7 Comment(0)
M
16

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

Monger answered 24/1, 2020 at 6:30 Comment(1)
Where can I find the official document of this? In the document of .NET framework?Dyl
M
8

If you just want to write the string to file:

$consumer_key ="xvz1evFS4wEEPTGEFPHBog"
$consumer_key |  Out-File c:\path\utf8file.txt -Encoding UTF8
Malvie answered 24/4, 2014 at 9:17 Comment(0)
B
0

$input = 'salut 🔥' $output = [System.Text.Encoding]::UTF8.GetString([System.Text.Encoding]::UTF8.GetBytes($input)) $output

Bette answered 13/3 at 16:27 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Sheen

© 2022 - 2024 — McMap. All rights reserved.