如何将字符串编码为Unicode Powershell

时间:2019-10-18 14:48:35

标签: powershell unicode

我需要将字符串字符转换为unicode。

为简单起见,如果我有以下字符串:"i_Id Mega (hex)", 我想对此进行编码并得到:"i_Id_x0020_Mega_x0020__x0028_hex"

我找不到在Powershell中执行此操作的方法。 欢迎所有帮助!

谢谢, TristanSébillet

2 个答案:

答案 0 :(得分:2)

这应该做到:

$inStr       = "i_Id Mega (hex)"
$outStr      = ""
$uniChars    = " ("
$removeChars = ")"

foreach( $char in [char[]]$inStr ) {

    if( $uniChars.Contains( $char ) ) {
        $outStr += '_x' + "{0:x4}" -f [char]::ConvertToUtf32([string]$char ,0) + '_'
    }
    elseif( !$removeChars.Contains( $char ) ) {
        $outStr += $char 
    }
}

$outStr

答案 1 :(得分:1)

或使用多个正则表达式-replace操作:

"i_Id Mega (hex)" -replace ' ', '_x0020_' -replace '\(', '_x0028_' -replace '\)'

结果:

i_Id_x0020_Mega_x0020__x0028_hex