Sunday, November 18, 2012

Powershell is my new favorite and I'm no longer missing Linux

I now officially use command lines and scripts in Windows more than I did in Linux. Before joining Microsoft, I had assumed that Powershell was a joke compared to the Linux terminal. I know that many programmers (still) think the same. It turns out I was very wrong.

Powershell supports a rich set of commands and programming capabilities. For virtually anything you can do with Linux terminal (using Bash or Python), you can do it as elegantly with Powershell. Here's a quick example with parsing xml files. (Just copy these commands directly into the console, i.e. no compiler or interpreter required.)
  • cat doc.xml will display the content of the xml file. Basic stuff.
  • [xml](cat doc.xml) will return an XML parser for the file doc.xml
  • ([xml](cat doc.xml)).SelectNodes("/foo/bar") will return an array of all nodes that share the path foo/bar
  • ([xml](cat doc.xml)).SelectNodes("/foo/bar") | where {$_.description} is a command pipeline which returns an array of all nodes that share the path foo/bar and that have the element description.
  • I can go on and on and do more powerful stuffs but you get the idea
One feature of Powershell that I particularly enjoy is the ability to call .NET libraries. Here's an example of random sampling a file where each line is an observation.
  1 function RandomSample($in,$out,$ratio) {   
  2      $random = new-object random
  3      ((cat $in) | ?{$random.nextDouble() -lt $ratio}) > $out  
  4 }
A command usage example is RandomSample input.csv output.csv 0.1

In this example, $random is a .NET object of type System.Random. You can also import your custom .NET types written in C++ or C#. So imagine how much you can do, quickly and elegantly, with Powershell. 

If you already like Powershell or if you're convinced by my post, read the blog by the scripting guy. In different occasions, I'll post my personal PS tips.


A few more words:
  1. This post focuses only on Powershell and scripting in Windows. There are many other great Windows tools  such as Visual Studio, .NET, C# (not a tool per se), Remote Desktop, Excel, Onenote, etc.  I'll describe them all at some point, given the right opportunities. All these good stuffs have contributed to my significantly boosted productivity.
  2. I haven't abandoned everything Linux, of course. At least I am still using gvim, which originated from the Linux community, as my main editor. By the way, I use gvim for Powershell programming. There is a nice gvim plugin for Powershell, if you use (or intend to use) gvim plus Powershell.

No comments:

Post a Comment