Saturday, January 02, 2010

PowerShell Cmdlet Naming Conventions Inside Modules

PowerShell cmdlets use a verb-noun naming pattern. To the extent possible, you should follow the same pattern when writing your own functions and scripts. This verb-noun naming is partly enforced by PowerShell, at least as far as the verbs to. MS has published an approved verbs list on MSDN.
With PowerShell V2, if you try to import cmdlets or modules that violates the verb naming convention, you’ll get a warning. Here’s an example module to demonstrate this. First, I create the file testmodule.psm1. I store this as testmodule.psm1, inside my modules folder:

  1. # Demo of badly named function 
  2. # and how PowerShell V2 deals with it 
  3.  
  4. function badly-named { 
  5.   "Inside the badly named function" 
  6.   } 
Look what happens when I try to import it:
PSH [C:\foo]: ls $Modules\testmodule
    Directory: Microsoft.PowerShell.Core\FileSystem::C:\Users\tfl\Documents\WindowsPowerShell\Modules\testmodule
Mode           LastWriteTime       Length Name
----           -------------       ------ ----
-a---      1/2/2010 12:36 PM          340 testmodule.psm1

PSH [C:\foo]: import-module testmodule -verbose

VERBOSE: The command name 'badly-named' includes an unapproved verb which might make it less discoverable
VERBOSE: Importing function 'badly-named'.
PSH [C:\foo]: badly-named
Inside the badly named function

Ss you can see, you can create a module with a badly named function just as you can create your own badly named cmdlets – and they work. But when you try to import such a module, PowerShelL v2 emits a warning error.
So for those of you getting into PowerShell, make sure that the functions you are putting into modules are named correctly!
Technorati Tags: ,,

No comments: