“Get” is Optional

There are many different shortcuts out there in PowerShell and I get exposed to new ones all of the time.  What I saw this past week at Microsoft Ignite was interesting to me because I am sure it has existed for a while.  It is the kind of shortcut that I normally wouldn’t use because I do follow the adage that when you are writing scripts that you should use the entire command, not an alias, and not the tip that I am going to show here.  In my opinion, it makes the script more readable which should be one of the top priorities that you have when writing code.

PowerShell have a standard convention of Verb-Noun for cmdlets.  So, if I want to get the information on a mailbox in Exchange, I use Get-Mailbox.  Likewise, if I need to modify its configuration, I use Set-Mailbox.  Pretty standard, nothing shocking.  However, the Get noun is an optional noun.  This does not only work with well-produced cmdlets, it works with any cmdlet.  I have been working on my own module lately and I did not do anything to make this work, but it does.

What is unfortunate, in my opinion, is that tab completion does not appear to work.  So, if I type “Mail” and press tab, nothing will happen unless there is somethat that begins with “Mail” in my path.  If the functionality were added, I could see it prepending the “Get-“ in front of it.

When could this work for making code more readable?  Maybe when you are doing something else that makes it less readable, like trying to make a one-liner.  In this case, it would shorten the one-liner and allow it to be seen on one line.  I would still avoid it.  The “wow” factor of making something happening in one line is of little value compared to the time saved in the future trying to understand what is happening.

Still very interesting that the PowerShell team has built all of the very capable features in that allow folks the ability to use PowerShell on their own terms.

FOLLOW UP: On top of making code less readable, it is [relatively] computationally expensive.  The way it works is by searching the paths in your system for the cmdlet as is and when it fails to find it, it runs the process again and prepends “Get-“ to it.  This is discussed in great detail further: Not Specifying a Verb in PowerShell is an Expensive Shortcut.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s