Putty alias

Here's a quick code post from my Powershell profile. I keep copying this around every time I set up a new system, so maybe it will be useful to others. And to me, since I can copy it off the web in the future rather than having to dig it up or recreate it.

Being an old-school UNIX guy, I get used to just typing ssh hostname to access my servers. So the Putty syntax of loading a profile annoys me. To that end, I wrote a few little functions to add to my Powershell $profile to address this. They just let me load a session by typing the familiar commands and don't require me to change syntax when using a profile versus connecting directly to a hostname.


# Suppress the assembly loading output
[System.Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null

function _puttyHasProfile {
   $profile_name = $args[0].ToLower()
   $profiles = Get-ChildItem HKCU:\Software\SimonTatham\PuTTY\Sessions\
   foreach ($p in $profiles) {
      $name = [System.IO.Path]::GetFileName($p.Name)
      # Putty stores spaces and other special characters URL encoded.
      $name = [System.Web.HttpUtility]::UrlDecode($name).ToLower()
      if ($name -eq $profile_name) {
         return 1
      }
   }
   return 0
}

function ssh {
   $profile_name = $args[0]
   if (_puttyHasProfile($profile_name)) {
      putty -load $profile_name
   } else {
      putty $args
   }
}

function sftp {
   $profile_name = $args[0]
   if (_puttyHasProfile($profile_name)) {
      psftp -load $profile_name
   } else {
      psftp $args
   }
}

You can reply to this entry by leaving a comment below. This entry accepts Pingbacks from other blogs. You can follow comments on this entry by subscribing to the RSS feed.

Add your comments #

A comment body is required. No HTML code allowed. URLs starting with http:// or ftp:// will be automatically converted to hyperlinks.