Monday, February 05, 2007

Expand/Collapse PowerShell Commands

I was listening the Bruce Payette interview on Hanselminutes and my interest really piqued when they were discussing aliases and being able to write really terse scripts.  It got me to thinking.  Wouldn't it be cool to be able to expand all the aliased command names in a script long enough for you to work on the script.  Then, when you are ready to put it back out there, you could collapse all the command names to short aliases.

Here is my first attempt:

   1:  function Expand-Command($Text)
   2:  {
   3:      $a = (alias $Text).Definition
   4:      if( $a.length -gt 0)
   5:      {
   6:          return $a
   7:      }
   8:      else
   9:      {
  10:          return $Text
  11:      }
  12:  }
  13:   
  14:  function Collapse-Command($Text)
  15:  {
  16:      $a = [string](alias | Where-Object { $_.Definition -eq $Text } | Sort-Object { Name.length })
  17:      if( $a.length -gt 0)
  18:      {
  19:          return $a.split(" ")[0]
  20:      }
  21:      else
  22:      {
  23:          return $Text
  24:      }
  25:  }
  26:   
  27:  function Expand-Script($script)
  28:  {    
  29:      $s = ""
  30:      Get-Content $script | ForEach-Object { ([string]$_).Split(" ") | ForEach-Object { $s += (Expand-Command($_) + " ") } }
  31:      return $s
  32:  }
  33:   
  34:  function Collapse-Script($script)
  35:  {
  36:      [string]$s = Get-Content $script
  37:        
  38:      Get-Command | ForEach-Object { $s = ($s -replace $_.Name, [string](Collapse-Command($_.Name))) }
  39:      return $s
  40:  }
  41:   
  42:  Collapse-Script("c:\\Dummy.ps1")
  43:  Expand-Script("c:\\Dummy.ps1")
 



So, what's going on? Let's start with the Collapse functions. The Collapse-Command function(lines 14-25) basically goes through all the aliases looking for the ones that match the command name that was passed in. Then it sorts them by their length and splits out the first available.  This way it will always pass back the shortest  command name.  In the Collapse-Script function(line 34-40), we loop through all the commands and then replace their names with the collapsed names.


The Expand-Command function(lines 1-12) acts pretty much the same as the Collapse-Command function.  The only difference is instead of searching on the alias definition, we search on the alias name.  The Expand-Script function(lines 27-32) acts a little differently than its counterpart.  It loops through all the individual lines and then through all the words, calling the Expand-Command function as it goes.


I tried to think like a PowerShell developer, not a C# developer for this one.  However, I don't think that it turned out very PowerShelly.  It is also ungodly slow.  I welcome any constructive ideas to make it better.   

No comments: