#requires -version 2.0 <# ----------------------------------------------------------------------------- Script: Translate-ToChar.ps1 Version: 1.0 Author: Jeffery Hicks http://jdhitsolutions.com/blog http://twitter.com/JeffHicks http://www.ScriptingGeek.com Date: 9/22/2011 Keywords: Comments: "Those who forget to script are doomed to repeat their work." **************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** ----------------------------------------------------------------------------- #> <# .Synopsis Take a text string and convert it to a CHAR Array. .Description Take a string message and convert it into an array of CHAR values or create a scriptblock using the -Join operator to reconstitute the original message. .Parameter Text The message to convert. The default is "PowerShell Rocks!" .Parameter Scriptblock Instead of writing an array of char values, write a scriptblock to the pipeline. For example, this would be the output using the default value for Text: -join [char[]](80,111,119,101,114,83,104,101,108,108,0,82,111,99,107,115,33) .Example PS C:\> c:\scripts\translate-char.ps1 "Nothing but shell!" -scriptblock -join [char[]](78,111,116,104,105,110,103,0,98,117,116,0,115,104,101,108,108,33) .Example PS C:\> $arr=c:\scripts\translate-char.ps1 "TGIF! Who's got the first round?" Save the CHAR array to a variable so it can be used later, perhaps like this: PS C:\scripts> write-host (-join [char[]]$arr) -fore green TGIF! Who's got the first round? #> [cmdletbinding()] Param( [Parameter(Position=0)] [ValidateNotNullOrEmpty()] [string]$Text="PowerShell Rocks!", [switch]$Scriptblock ) #create CHAR mapping hash table $map=@{} 33..125 | foreach { $map.Add([string]$_,[char]$_)} #create an empty array to hold the CHAR values $values=@() $text.ToCharArray() | foreach { #because $_ will change, save the current piped in character as a variable $ltr=$_ [int]$i=($map.getEnumerator() | where {$_.value -ceq $ltr }).Name #add the value to the array $values+=$i } if ($ScriptBlock) { #write a scriptblock to the pipeline #set the output field separator to a comma $ofs="," #create a variable so we get variable expansion of $values $t="-join [char[]]($values)" #put it back together as a script block and write to the pipeline [scriptblock]::Create($t) } else { #write value array to the pipeline $values } #end