22

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

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
user3562182
  • 365
  • 1
  • 5
  • 8

3 Answers3

31

Try this instead:

$enc = [System.Text.Encoding]::UTF8
$consumerkey ="xvz1evFS4wEEPTGEFPHBog"
$encconsumerkey= $enc.GetBytes($consumerkey)
Cellcon
  • 1,245
  • 2
  • 11
  • 27
justpaul
  • 366
  • 3
  • 4
14

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

cliffclof
  • 294
  • 2
  • 11
8

If you just want to write the string to file:

$consumer_key ="xvz1evFS4wEEPTGEFPHBog"
$consumer_key |  Out-File c:\path\utf8file.txt -Encoding UTF8
Raf
  • 9,681
  • 1
  • 29
  • 41