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!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: