The other day someone came over to my desk and asked me how they could programatically invoke the "Find Computer" function of the Windows shell. Normally you just press CTRL-WINDOWS-F and up pops an Explorer window ready for searching. I didn't have a quick answer for him... so I immediately took up the challenge to figure it out.
After a couple dead ends I started looking at Windows Script Host (WSH). It allows you to write VB or JavaScript to access the ActiveX API of a Windows application. After a bit of googling I found the "Shell.Application" documentation on MSDN. After futzing around with Javascript for a few minutes I started thinking that I should be able to do the same things with Ruby. So with a little more searching I discovered that by adding "require 'win32ole'" at the top of my ruby script I could instantiate an instance of "Shell.Application".
The only problem left was finding the right API call. A three line Ruby script like this gave me a list of methods:
require 'win32ole'
wsh = WIN32OLE.new('Shell.Application')
wsh.ole_methods.collect{|m| m.to_s}.sort.each{|m| puts m}
A quick change and my final script looked like:
require 'win32ole'
wsh = WIN32OLE.new('Shell.Application')
wsh.FindComputer()
or in JavaScript:
wsh = WScript.CreateObject("Shell.Application");
wsh.FindComputer();
If you want to take this scripting stuff to the next level I suggest you go check out David Mullet's "Ruby on Windows" blog. He describes some of the same things I just demonstrated above and goes into a lot greater depth about how to use Ruby to script think like Word and Excel.
And in case you're wondering why I had to use Ruby to get a list of methods instead of just looking it up in MSDN, well just try looking at the MSDN page I referenced above with Firefox instead of IE.... That's right... the site navigation only works correctly in Internet Explorer.
No comments:
Post a Comment