Monday, November 26, 2007

Windows PowerShell

If you haven't heard of PowerShell, its a windows command line shell which uses .NET objects for everything, and I'm a fan.

For example, in cmd or bash or whatever, when you type dir or ls you get a text display of a directory's contents. The command outputs formated text. In PowerShell if you type dir you get System.IO.DirectoryInfo and System.IO.FileInfo objects. That's right .NET objects. By default, those types get displayed to the screen in a table format. Wanna change how the output is formated? Pipe it to one of the format commands: dir | format-wide

There are three incredibly cool things here:
  • The command outputs .NET objects
  • The display is independent of the command
  • The pipe command inputs .NET objects from one command to another
This is leaps and bounds better than any other command line shell I've ever used. You don't have to do a bunch of text manipulation to get at the information you want, just call the property. Or call a method. If it's .NET you can do it. And that means you can use your own .NET objects from the command line too. Also, you don't have to learn the formating behavior of many different commands. They're all consistent because they all output .NET objects which are formated with the three format-* commands.

If you've spent much time with a command line you should be starting to see how powerful this is. Here's an actual example. I needed to find out what file extensions people were putting into the document management application here at work. My first thought was to write a Ruby script that would iterate through all the files under a given directory (including subdirectories) and add the extension to an array (if it wasn't already added), then display the array to the command line. Pretty simple script.

Then I thought, I bet I could use PowerShell do this.
dir -recurse | select-object extension -unique

select-object is a command that pulls out a given property from an object. dir | select-object extension will show you the extension for every file in the current directory. Adding the -unique flag will remove duplicate extensions, showing you each extension exactly once.

I wont turn this into a PowerShell tutorial, for that you can refer to Scott Hanselman on PowerShell or just download it and read the documentation it comes with, which is actually quite good. Then start diving into the help, which is also quite good.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.