Sunday, 2 May 2010

Get-UTF8Encoding

  1. <# 
  2. .SYNOPSIS 
  3.     This script implements an MSDN Encoding example in PowerShell  
  4. .DESCRIPTION 
  5.     This script creates an encoding plus a Unicode string then 
  6.     manipulates it as per the C# sample. 
  7. .NOTES 
  8.     File Name  : Get-UTF8Encoding 
  9.     Author     : Thomas Lee - tfl@psp.co.uk 
  10.     Requires   : PowerShell Version 2.0 
  11. .LINK 
  12.     This script posted to: 
  13.         http://pshscripts.blogspot.com/2010/05/get-utf8encoding.html 
  14.     MSDN Sample posted at: 
  15.         http://msdn.microsoft.com/en-us/library/system.text.utf8encoding.aspx  
  16. .EXAMPLE 
  17.     PSH [C:\foo]: .\Get-UTF8Encoding.ps1
  18.     Original string:This unicode string contains two characters with
  19.     codes outside an 8-bit code range, Pi (π) and Sigma (Σ). 
  20.     Encoded bytes: 
  21.     <long table omitted> 
  22.     Decoded bytes: 
  23.     This unicode string contains two characters with codes outside an
  24.     8-bit code range, Pi (π) and Sigma (Σ). 
  25. #> 
  26. #  Start of Script 
  27. # Create a UTF-8 encoding. 
  28. $utf8 = New-Object System.Text.utf8encoding 
  29. $unicodeString
  30.             "This unicode string contains two characters "
  31.             "with codes outside an 8-bit code range, "
  32.             "Pi (" + [char] 0x03a0 + ") and Sigma (" + [char] 0x03a3 + ")." 
  33. "Original string:{0}" -f $unicodeString 
  34.  
  35. # Encode the string. 
  36. $encodedBytes = $utf8.GetBytes($unicodeString
  37. "" 
  38. "Encoded bytes:" 
  39. foreach($b in $encodedBytes) {"[{0}]" -f $b
  40.  
  41. # Decode bytes back to string 
  42. # Notice Pi and Sigma characters are still present 
  43. $decodedString = $utf8.GetString($encodedBytes
  44. "";"Decoded bytes:" 
  45. $decodedString    
  46. # End of Script 

No comments: