Using System.Char Static Methods

Event 5 in the Scripting Games dealt with testing whether or not a password is secure or not.  Among many qualifications, the password had to contain at least one digit, at least one upper case character and at least one lower case character. There also needed to be a check to see if the password contained any non-alphanumeric characters, such as $%^ or (.

All these could be dealt with using regular expressions, but regex skills are weak at best, so I always default to check and see if if someone has done it for me already. Sure enough, there are a bunch of static methods for System.Char that we can use.

   1: [char]::IsUpper()
   2: [char]::IsLower()
   3: [char]::IsDigit()
   4: [char]::IsLetterOrDigit()

From these we can build a filter that will pass the string if it meets the criteria. For the sake of example, lets build “Select-ContainsUpper”

   1: # Create a filter that can be used in a pipeline
   2: filter Select-ContainsUpper {
   3:     
   4:     # coerce the string into an array of chars and then pass each one to IsUpper
   5:     # IsUpper returns $TRUE or $FALSE for each char
   6:     # So ContainsUpper now contains an array of a bunch of Booleans
   7:     $containsUpper = $_.toCharArray() | % {[char]::IsUpper($_)}
   8:     
   9:     # if any char was uppercase, some element in ContainsUpper will be $TRUE
  10:     if ($containsUpper -contains $TRUE) {$_}
  11:     }
  12:     
  13: "one","Two","5","ContainsUpperCase","all-lower-case" | Select-ContainsUpper

Building Select-ContainsDigit and the others is left as an exercise to the reader.

You could also quite easily build a function that takes the string as a password, but lately I have been big on using filters and then putting them all together in a nice pipeline for the sake of clarity and a nice overall PowerShelly look.

Advertisements

One Response to “Using System.Char Static Methods”

  1. Alliepz Says:

    thats it, bro

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: