Wednesday, February 18, 2009

Get-ChildItem (dir) Results Color-Coded by Type

I always liked the way you can color code your directory items in Linux. I always set alias ls='ls -al --color' the minute I log into a system. It makes it easier to scan results and instantly know some extra data about the items in a directory.

I decided that I wanted to be able to do this in PowerShell. If you do a few Google searches you'll see I'm not the first, and it's not without it's quirks, but I decided not to worry about being true to the Linux form and just go with the spirit of what I wanted to get out of it. I've included the code below. There are a couple of things of note, though it's mostly waht I wanted:
  • I would rather if the header at the top wasn't always the same color as the first item, but I can't think of any way around that.
  • Rather than coloring results by permissions, I've colored them by type, with four major types: Directory, Executable, Compressed, and Text.
  • If you use sort or select you'll lose the color, but otherwise the color change should last down the pipeline for each obect.
  • This was made to be used with v2.0 CTP3 of PowerShell. If you want to use it with earlier versions you have to remove the documentation block at the beginning of the function, but you also lose the ability to use the help command to find out more about the function.
  • Note that I compile the Regular Expressions at the beginning. If I just used -match to check the regular expressions for each file, I would add a lot of extra overhead, because the regular expressions would be compiled each time a file was checked. This boosts performance, and there is an analogue in each language that supports regular expressions.