How do I encode Unicode character codes in a Power

2019-01-14 00:13发布

How can I encode the Unicode character U+0048 (H), say, in a PowerShell string?

In C# I would just do this: "\u0048", but that doesn't appear to work in PowerShell.

3条回答
祖国的老花朵
2楼-- · 2019-01-14 00:54

Replace '\u' with '0x' and cast it to System.Char:

PS > [char]0x0048
H

You can also use the "$()" syntax to embed a Unicode character into a string:

PS > "Acme$([char]0x2122) Company"
AcmeT Company

Where T is PowerShell's representation of the character for non-registered trademarks.

查看更多
地球回转人心会变
3楼-- · 2019-01-14 00:55

Maybe this isn't the PowerShell way, but this is what I do. I find it to be cleaner.

[regex]::Unescape("\u0048") # Prints H
[regex]::Unescape("\u0048ello") # Prints Hello
查看更多
一夜七次
4楼-- · 2019-01-14 00:56

According to the documentation, PowerShell Core 6.0 adds support with this escape sequence:

PS> "`u{0048}"
H

see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_special_characters?view=powershell-6#unicode-character-ux

查看更多
登录 后发表回答