Autocompleting ssh, rake, cap command parameters using PowerShell

I have mentioned in my previous posts that PowerShell has excellent and customizabme autocompletion support.
And some awesome plugins like powertab exist to take this functionality to another level.
Here is one easy way you can customize autocompletion easily by writing a couple of lines of code.

Open your PowerShell profile file (for help see here) and create a function with name "global:TabExpansion" in it.
This function basically overrides default autocompletion and sends your values to the prompt. For example for it to read your ssh files and display hosts in it the function would look something like this:

# customized tab expansion
function global:TabExpansion {
  param($line, $lastWord)
  
  if ($line -match 'ssh'){
    return cat C:\Users\Gaurav\.ssh\config | Select-String '^Host ' | % { if($_.Line -match "^Host ($lastword\S*)" ){ $matches[1] }}
  }
}

Here it is just parsing the config file and running it through a regular-expression and returning the results as an array. Here is what a typical ssh config file looks like:

Host blog
  User username
  HostName sitename.com
  IdentityFile ~/.ssh/id_dsa
  
Host blog_2
  User username
  HostName sitename.com
  IdentityFile ~/.ssh/id_dsa

 

Here is what the output looks like if I write “ssh ” and the press tab key twice:

image

image

 

Also this same function can easily be modded to autocomplete for ruby/rails commands like rake and cap.

Here is is my complete function:

# customized tab expansion
function global:TabExpansion {
  param($line, $lastWord)
  
  if ($line -match 'ssh'){
    return cat C:\Users\Gaurav\.ssh\config | Select-String '^Host ' | % { if($_.Line -match "^Host ($lastword\S*)" ){ $matches[1] }}
  }
  elseif ($line -match 'rake'){
    rake -T | % { if($_ -match "^rake ($lastword\S*)" ){ $matches[1] }}
  } 
  elseif ($line -match 'cap'){
    cap -T | % { if($_ -match "^cap ($lastword\S*)" ){ $matches[1] }}
  }
}

Sunday, November 23rd, 2008 powerpoint, rails, ssh

No comments yet.

Leave a comment