Generating All Case Combinations in PowerShell

At work, a software package that I’m dealing with requires that lists of file extensions for whitelisting or blacklisting be case-sensitive. I’m not sure why this is the case (no pun intended), but it is not the only piece of software that I’ve used with this issue.

What that means is that if you want to block .EXE files, you need to include 8 different variations of EXE (exe, exE, eXe, eXE, Exe, ExE, EXe, EXE). It wasn’t too hard to come up with those, but what about ps1xml? 64 variations.

For fun, I wrote a small PowerShell function to generate a list of the different possibilities. It does this by looking at all of the binary numbers with the same number of bits as the extension, interpreting a 0 as lower-case and 1 as upper case.

Here it is:

function Get-ExtensionCases{
param([string]$ext= 'exe')

  $vars=$ext.ToLower() ,$ext.ToUpper() 

  $powers=0..$ext.length | foreach {  [math]::pow(2,$_) }
  foreach($i in 0..([math]::Pow(2,$ext.length)-1)){
      (0..($ext.length-1)|foreach {$vars[($i -band $powers[$_])/$powers[$_]][$_]}) -join ''
  } 
}

I pre-calculate the relevant powers of two in $powers, since we use them over and over again. I also do the upper/lower once at the beginning and do some (gross) indexing to get the proper one.

Here’s the output for exe:

It was a fun few minutes. Watching longer output scroll by can even be somewhat mesmerizing.

Let me know what you think

–Mike

P.S. PowerShellStation was named one of the top 50 PowerShell blogs! Thanks to everyone for stopping by and listening to my rambling.

4 Comments

  1. Pingback: Generating All Case Combinations in PowerShell - How to Code .NET

  2. ps1xml only has 32 variations – there’s no such thing as capital 1 🙂

    (Get-ExtensionCases ‘ps1xml’).Count
    64

    (Get-ExtensionCases ‘ps1xml’ | select -Unique).Count
    32

    Pretty clever function though. I’m still trying to process the code to tweak it to account for number, symbols, etc. that can’t be capitalized.

    Scott
    (from SWMO Powershell group)

  3. Try this on for size. It’s a little more brute forcey and not as ‘cool’, but it’s much faster and unique is built in.

    function Get-ExtensionCases {
    param([string]$ext = ‘exe’)
     
    $vars=$ext.ToLower(), $ext.ToUpper()
     
    for ($i = 0; $i -lt $ext.Length; $i++) {
    $expression += “for (`$L$i = 0; `$L$i -le ” + [int][bool]($vars[0][$i] -band -bnot $vars[1][$i]) + “; `$L$i++) {”
    }
    for ($i = 0; $i -lt $ext.Length; $i++) {
    $expression += “`$vars[`$L$i][$i] + ”
    }
    $expression += ‘””‘ + “}” * $ext.Length
    Invoke-Expression $expression
    }

Comments are closed.