preload
Listing MS Project tasks using Ruby Installing the Watir Gem under Windows 7
Jan 11

I’m not sure if I picked this up from another website or not, but its been in my bag of tools almost as long as I’ve been programming in Ruby :)

#!c:\ruby\bin\ruby.exe -w

require 'exo/iswindows'

def which(pgm)
   @path = ENV['PATH'].split(/;/)
   @path.each { |cdir|
      cmd = cdir + "\\" + pgm
      if test(?s, cmd)
        return cdir
      end
    }
  return nil
end

if __FILE__ == $0
   aa = ARGV[0]
   if RUBY_PLATFORM.isWindows?
     if (! aa.index("."))
       aa += ".exe"
     end
   end

   rc = which(aa)
   if (rc)
     print rc
   else
     print "NOT FOUND in PATH=" + ENV['PATH']
   end
end

Put the which.rb file in the path somewhere and it works the same way as the unix command of the same name:

C:\Server8\Dev\Ruby>which explorer
C:\WINDOWS
C:\Server8\Dev\Ruby>which ruby
c:\ruby\bin
C:\Server8\Dev\Ruby>which java
C:\WINDOWS\system32
C:\Server8\Dev\Ruby>which perl
C:\Perl\bin
C:\Server8\Dev\Ruby>which blatt.exe
NOT FOUND in PATH=C:\Program Files\Windows Resource Kits\Tools\;C:\Program Files\CollabNet Subversion Client;c:\program files\imagemagick-6.4.3-q8;C:\Perl\site\bin;C:\Perl\bin;c:\ruby\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\ibm\gsk7\bin;C:\Program Files\ibm\gsk7\lib;C:\Program Files\IBM\Informix\Client-SDK\bin;C:\Program Files\MySQL\MySQL Server 5.0\bin;C:\Program Files\Common Files\Roxio Shared\9.0\DLLShared\;C:\Program Files\Windows Imaging\;C:\Program Files\QuickTime\QTSystem\;C:\Java\SDK\bin
SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon

3 Responses to “A Unix ‘Which’ command for Windows”

  1. Timm Says:

    Where does is this ‘exo/iswindows’ library come from?

  2. john Says:

    Hi Timm :)
    its actually one of my helper libraries. Its nothing more than an extension to the ‘String’ class that looks for a windows string:
    Class String
    def isWindows?
    if self =~ /(:?mswin|win32|mingw)/
    return true
    end
    return false
    end
    end

  3. David Says:

    John try this:

    if RUBY_PLATFORM['win']

    and you won’t need an external library, && basically does the same thing.

    For JRuby (which is ‘java’ for platform) you have to call a Java function, I think I have it on my github if not I’ll put it there shortly.

Leave a Reply