ASCII Reinvented

I mentioned earlier that I had told a colleague about using Hashtables in PowerShell and C#.  Later on in the afternoon, he came across a situation where he needed to generate a random string of characters.

He came up with this little snippet of code.  (I think he may have a been a little high on Hash . . . . . tables)

   1: function new-array {$args}                                                                                        
   2: $CharacterArray = new-array A B C D E F G H I J K L M N O P Q R S T U V X Y Z;                                    
   3: $CharacterHashTable = new-object System.Collections.Hashtable                                                                                                                                                                     
   4: for ($i=0; $i -ilt $CharacterArray.Count; $i++) {$CharacterHashTable.Add($i, $CharacterArray[$i])}                
   5: $randomNumber = new-object System.Random                                                                          
   6: $randomCharacter = $CharacterHashTable[$,25)]                         

"Wow!  That is great!  You basically reinvented ASCII !"

Then I showed him this neat little trick :)

   1: PS >  [char]65
   2: A

He came back with these two lines to generate a random character.

   1: $randomObject = New-Object System.Random
   2: $randomChar = [char]$,90)

It turns out that if you know ASCII exists, it can indeed be used to generate random characters :)

However, I have to give some credit for coming up with a neat little subset of ASCII in a couple lines of PowerShell. Not too shabby!

Comments (1) -

This was a fun post! It got me playing around with this and I came up with the following...

$rnd = New-Object System.Random
$charsArray[($rnd.Next(0,$charsArray.Count - 1))]

This will pull a random item from within the $charsArray variable. This could contain upper- and lower-case letters, for example. You can tehn wrap this up in a little function and use it like:

function Get-RandomChar {
  param([string]$string = (Read-Host "Enter list of characters"))
  $rnd = New-Object System.Random
  $charsArray = $string.ToCharArray()
  $charsArray[($rnd.Next(0,$charsArray.Count - 1))]

Get-RandomChar $chars

Fun stuff! Your posts have been great fun and have led me to explore things I may not have otherwise looked at! Keep them coming!

Comments are closed