0

I need to convert a string characters to unicode.

To be simple, if i have this string : "i_Id Mega (hex)", i want to encode this and get : "i_Id_x0020_Mega_x0020__x0028_hex"

I don't find a way to do this in powershell. All help is welcome !

Thanks, Tristan Sébillet

1
  • 1
    You apparently want to replace space characters with _x0020_, open brackets with _x0028_ and remove closing round brackets? What have you tried already and what failed? Commented Oct 18, 2019 at 14:55

2 Answers 2

2

This should do it:

$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
Sign up to request clarification or add additional context in comments.

Comments

1

Or use several regex -replace actions:

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

Result:

i_Id_x0020_Mega_x0020__x0028_hex

1 Comment

That's what i want but i need to do it for all special characters. So the -replace solution is a bit long..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.