Learning PowerShell Part 3

04/26/09

Learning PowerShell Part 3

First, I found Keith Hill’s Free PowerShell EBook that I’d previously mentioned quite valuable. Recommended.

Here’s another reference you’ll want: Bruce Payette’s Windows PowerShell Refcard.

And a few more links:

Creating Cmdlets

This is a relatively advanced topic, and is not required to use PowerShell. However, it’s something I’m interested in. I’d like to try creating DSLs (Domain-Specific Languages) in PowerShell.

Allegedly, the Windows PowerShell SDK is required. The installation instructions are unnecessarily complex. Why can’t Microsoft give us a “download just the PowerShell SDK and nothing else” link? Why do I have to install the Windows Server 2008 SDK?

Once you’ve installed the relevant portions (read the download instructions carefully), you’ll then need to locate the relevant DLL to reference. If you read way down on this article on the Windows PowerShell Blog, you’ll learn that “Reference assemnblies are installed as part of SDK installation under ‘Program Files\Reference Assemblies\Microsoft’". On my system, this is:

  C:\Program Files\Reference Assemblies\Microsoft\
    WindowsPowerShell\v1.0

and the assembly that your project must reference is:

  System.Management.Automation.dll

Oddly, the folder timestamp showed that it was created on my PC long before I installed the SDK. I checked another PC that just had PowerShell and Visual Studio installed and found this assembly at the above location. In other words, I do not believe that you need to install the SDK.

To create a cmdlet in C# or VB.NET:

  1. In Visual Studio, create a Class Library project
  2. Add a reference to System.Management.Automation.dll (see above)
  3. Add a reference to System.Configuration.Install (from the .NET tab)
  4. See the sample code on MSDN
  5. Build the project

To install the new cmdlet in PowerShell:

  1. As per How to Register Cmdlets, register the snap-in with installutil. Note that the following command line is correct even for .NET 3.5:
    C:\Windows\Microsoft.NET\Framework\v2.0.50727\installutil MyCmdlet.dll
  2. Verify in PowerShell that it’s registered:
    Get-PSSnapin -Registered
  3. Add it to PowerShell:
    Add-PSSnapin [Name]
  4. Optionally export it to make it permanent

When testing, you can use the /u switch with installutil to uninstall a snap-in.

Just a thought, but wouldn’t it have been simpler to have a PlugIn folder where you could drop DLLs that PowerShell would recognize and load on startup? The current process smacks of COM to me.

You can also write your own provider. Get-PSProvider lists the current providers, which allow PowerShell to treat various hierarchies like file systems on drives.


Your Host: webmaster@truewill.net
Copyright © 2000-2013 by William Sorensen. All rights reserved.