Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Unicode Emoji in PowerShell

I would like to display a Unicode Emoji like U+1F4A9 in PowerShell. I know this works only inside the ISE console but I don't know how.

What I tried so far:

$CharBytes = [System.Text.Encoding]::Unicode.GetBytes("πŸ’©")

This will return 61, 216, 169, 220. But this can not be the representation of 0x1F4A9?

When I try

[BitConverter]::GetBytes(0x1F4A9)

I'll get a different set of Bytes: 169, 244, 1, 0. Converting them into a Unicode char results to a

So my question is: How can I display any Unicode char in PowerShell ISE (and may be in the console window too)?

like image 816
PeterXX Avatar asked Aug 10 '17 21:08

PeterXX


3 Answers

Ok, that was easy: I have to use UTF32 instead of Unicode:

$CharBytes = 169, 244, 1, 0
[System.Text.Encoding]::UTF32.GetString($CharBytes)
like image 152
PeterXX Avatar answered Nov 04 '22 03:11

PeterXX


Here's another way demonstrating the high and low surrogates, because the code point has over 16 bits. The result is actually a 2 character string. If you try to display each character individually, it will look like garbage.

$S = 0x1f600
$S = $S - 0x10000
$H = 0xD800 + ($S -shr 10)
$L = 0xDC00 + ($S -band 0x3FF)
$emoji = [char]$H + [char]$L
$emoji

πŸ˜€

Reference: http://www.russellcottrell.com/greek/utilities/SurrogatePairCalculator.htm

Or to get the code back:

($emoji[0] - 0xD800) * 0x400 + $emoji[1] - 0xDC00 + 0x10000 | % tostring x

1f600
like image 42
js2010 Avatar answered Nov 04 '22 03:11

js2010


Another way to do this in one line is:

[char]::ConvertFromUtf32(0x1F4A9)

Even better still:

"`u{1F4A9}"

Edit:

Above, "`u{}" is a way to escape a unicode character to be interpreted by Powershell. This is built into Powershell itself.

See: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_special_characters?view=powershell-7.1#unicode-character-ux

like image 40
MrHockeyMonkey Avatar answered Nov 04 '22 03:11

MrHockeyMonkey