如何在PowerShell字符串文字中编码Unicode字符代码?

时间:2009-06-29 05:32:19

标签: powershell unicode string-literals unicode-literals

如何在PowerShell字符串中编码Unicode字符U + 0048(H)?

在C#中我会这样做:"\u0048",但这似乎不适用于PowerShell。

7 个答案:

答案 0 :(得分:53)

将'\ u'替换为'0x'并将其强制转换为System.Char:

PS > [char]0x0048
H

您还可以使用“$()”语法将Unicode字符嵌入到字符串中:

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

其中T是PowerShell对非注册商标字符的表示。

答案 1 :(得分:13)

根据文档,PowerShell Core 6.0增加了对此转义序列的支持:

<script>
 $(document).on('change','#liste_tur_filter, #liste_il_sec_filter', function(){

   filter_1_value = $('#liste_tur_filter').val();
   filter_2_value = $('#liste_il_sec_filter').val();

     $('.urun_container').show();

   if(filter_1_value != null)
   $('.liste_tur').filter('[name!='+ filter_1_value +']').parent().hide();

   if(filter_2_value != null)
   $('.sehir').filter('[name!='+ filter_2_value +']').parent().hide();

           });
 </script>

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

答案 2 :(得分:6)

也许这不是PowerShell方式,但这就是我的工作。我觉得它更干净。

[regex]::Unescape("\u0048") # Prints H
[regex]::Unescape("\u0048ello") # Prints Hello

答案 3 :(得分:1)

对于仍然使用5.1并希望使用更高阶Unicode字符集(对于这些答案均无效)的我们,我做了此功能,因此您可以像这样简单地构建字符串:

'this is my favourite park ',0x1F3DE,'. It is pretty sweet ',0x1F60A | Unicode

enter image description here

#takes in a stream of strings and integers,
#where integers are unicode codepoints,
#and concatenates these into valid UTF16
Function Unicode {
    Begin {
        $output=[System.Text.StringBuilder]::new()
    }
    Process {
        $output.Append($(
            if ($_ -is [int]) { [char]::ConvertFromUtf32($_) }
            else { [string]$_ }
        )) | Out-Null
    }
    End { $output.ToString() }
}

请注意,将这些内容显示在控制台中是whole other problem,但是如果要输出到Outlook email或Gridview(如下),它将可以正常工作(因为utf16是原生的)。 NET接口)。

enter image description here

这也意味着,如果您更喜欢十进制,因为您实际上不需要使用0x(十六进制)语法来生成整数,因此还可以轻松输出普通控制(不一定是unicode)字符。 'hello',32,'there' | Unicode会将non-breaking space放在两个词之间,就像您使用0x20一样。

答案 4 :(得分:1)

要使其适用于BMP之外的字符,您需要使用Char.ConvertFromUtf32()

'this is my favourite park ' + [char]::ConvertFromUtf32(0x1F3DE) + 
'. It is pretty sweet ' + [char]::ConvertFromUtf32(0x1F60A)

答案 5 :(得分:0)

使用PowerShell的另一种方法。

newpage div

使用命令$Heart = $([char]0x2665) $Diamond = $([char]0x2666) $Club = $([char]0x2663) $Spade = $([char]0x2660) Write-Host $Heart -BackgroundColor Yellow -ForegroundColor Magenta 阅读有关它的全部信息。

答案 6 :(得分:0)

请注意,一些像?这样的字符可能需要打印“双符文”:

   PS> "C:\foo\bar\$([char]0xd83c)$([char]0xdf0e)something.txt"

将打印:

   C:\foo\bar\?something.txt

您可以在此处的“unicode escape”行中找到这些“符文”:

   https://dencode.com/string
相关问题