PowerShell loves enumerations

One of the things that make PowerShell oh-so-great is its tight integration with .NET Framework. As a simple example, in the framework there are many pre-define values, often stored as enumerated types. Enums are great because they allow us to define a set of values and then let the user (or program) choose among these values.

Another great thing with PowerShell is that it makes command arguments ‘pickable’ on the command line. So if I’m running a command and I am unsure of which arguments can be used I can simply press tab and I will se the first valid parameter value. Let me show you the simple beauty of Enums together with PowerShell scripts.

function Get-SpecialFolderPath
{
  param ( [System.Environment+SpecialFolder]$SpecialFolder )
  return [System.Environment]::GetFolderPath($SpecialFolder)
}

This function takes one argument, the alias of a special folder, and returns the physical location of the special folder. The special folders that Windows knows about are define in the enumeration Environment.SpecialFolder. You can use the function like this:

Get-SpecialFolderPath -SpecialFolder Cookies
C:\Users\Joakim\AppData\Local\Microsoft\Windows\INetCookies

This in itself may not impress you (me neither:-)). But when you use this function toghether with your own function or other PowerShell cmdlets it becomes a great help for the user. Let’s say you want to quickly check what is in the users Cookie folder. How would you know where the cookies are stored? With this function you don’t, it is enough to type:

Get-SpecialFolderPath *tab*

As this is a static blogpost I can’t show you what happens when I press the key. but what does happen is that you will get the first value in the SpecialFolder enumeration, “Admintools”. Press tab again and you’ll get the second value which is “ApplicationData”. Another press of the tab key gies you “CDBurning” and so on. You can of course avoid pressing tab many times by providing part of the name of the folder your are looking for:

Get-SpecialFolderPath *tab*

When you press tab this will expand to:

Get-SpecialFolderPath Cookies

A more relevant example: If you want to list all items on the users desktop you can combine Get-ChildItem with Get-SpecialFolder as this:

Get-ChildItem (Get-SpecialFolderPath Desktop)

This will give you a listing of all items in your dekstop folder. Again, the beauty is that you do not need to know the exact path to the Desktop folder.

Using enumerations to get input can really make your PowerShell scripts a lot easier to use and safer. So I hope you take some time to play around with using enumerations with your functions and cmdlets!