Expand-Alias for PowerShell Integrated Scripting Environment

January 3, 2009

in PowerShell,PowerShell ISE

Get your PowerShell code ready for production by expanding your shorthand alias syntax.

Use the shorthand approach to knock out your scripts. Then expand them. Makes your code more readable and maintainable in the long run.

image

 

 

 

 

 

 

Press Ctrl+Shift+E

image

 

 

 

 

 

 

How To

Add this code to your Microsoft.PowerShellISE_profile.ps1

Function Expand-Alias {
  $content=$psise.CurrentOpenedFile.Editor.text
  [System.Management.Automation.PsParser]::Tokenize($content, [ref] $null) |
    Where { $_.Type -eq 'Command'} |
    Sort StartLine, StartColumn -Desc |
    ForEach {
      if($_.Content -eq '?') {
        $result = Get-Command '`?' -CommandType Alias
      } else {
        $result = Get-Command $_.Content -CommandType Alias -ErrorAction SilentlyContinue
      }

      if($result)
      {
        $psise.CurrentOpenedFile.Editor.Select($_.StartLine,$_.StartColumn,$_.EndLine,$_.EndColumn)
        $psise.CurrentOpenedFile.Editor.InsertText($result.Definition)
      }
    }
}

if( -Not ($psISE.CustomMenu.Submenus | ?{$_.DisplayName -eq 'Expand Alias'}) ) {
    $null = $psISE.CustomMenu.Submenus.Add("Expand Alias", {Expand-Alias}, 'Ctrl+Shift+E')
}

Update

Thanks to Johannes Rössel who emailed the updated version that works with the PowerShell version shipped with Win 7 RC.

   1: Function Expand-Alias {

   2:   $content=$psise.CurrentFile.Editor.text

   3:   [System.Management.Automation.PsParser]::Tokenize($content, [ref] $null) |

   4:     Where { $_.Type -eq 'Command'} |

   5:     Sort StartLine, StartColumn -Desc |

   6:     ForEach {

   7:       if($_.Content -eq '?') {

   8:         $result = Get-Command '`?' -CommandType Alias

   9:       } else {

  10:         $result = Get-Command $_.Content -CommandType Alias -ErrorAction SilentlyContinue

  11:       }

  12:       if($result)

  13:       {

  14:         $psise.CurrentFile.Editor.Select($_.StartLine,$_.StartColumn,$_.EndLine,$_.EndColumn)

  15:         $psise.CurrentFile.Editor.InsertText($result.Definition)

  16:       }

  17:     }

  18: }

  19:  

  20: if( -Not ($psISE.CustomMenu.Submenus | ?{$_.DisplayName -eq 'Expand Alias'}) ) {

  21:   $null = $psISE.CurrentPowershellTab.AddOnsMenu.Submenus.Add("Expand Alias", {Expand-Alias}, 'Ctrl+Shift+E')

  22: }

{ 1 trackback }

PowerShell ISE-Cream
02.03.09 at 7:28 pm

Comments on this entry are closed.

Contrat Creative Commons

© 2007-2012, Doug Finke