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)?
Ok, that was easy: I have to use UTF32 instead of Unicode:
$CharBytes = 169, 244, 1, 0
[System.Text.Encoding]::UTF32.GetString($CharBytes)
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With