How to: Build a SharePoint 2010 PowerShell Cmdlet

Posted Monday, April 26, 2010 10:58 AM by CoreyRoth

One thing that is getting a lot of attention in SharePoint 2010, is the use of PowerShell.  It’s too cool and you really have a lot of power (no pun intended) to automate just about anything in SharePoint.  In fact Kyle Kelin (@spkyle) are speaking this weekend about it at SharePoint Saturday Houston (#spshou).  The Microsoft.SharePoint.PowerShell snapin comes with over 500 commands, but you might want to create your own.  Today’s post will show you how to get started.  There are a lot of great posts out there on how to build a regular PowerShell cmdlet, but I wanted to build one that focused specifically on building one for SharePoint. 

Start by creating a new class library project in Visual Studio 2010.  It’s too bad there isn’t a built-in project template, because there are a number of references you must add.  Several of these references don’t show up in the references browser either, so you have to actually specify the path directly from the GAC (or get a copy of it from somewhere).  I’ll include full paths for most things to make it easier for you to add references.

  • System.Management.Automation.dll (C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll)
  • System.Configuration.Install.dll (C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Configuration.Install.dll)
  • Microsoft.SharePoint.dll (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.SharePoint.dll)
  • Microsoft.SharePoint.PowerShell.dll (C:\Windows\assembly\GAC_MSIL\Microsoft.SharePoint.PowerShell\14.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Powershell.dll)

As I mentioned, some of these you will find in the Add Reference browser, but some you will not.  System.Configuration.Install.dll is only required if you plan on making your assembly a Snapin (we’ll talk about that in a bit).  For some reason, Microsoft.SharePoint.PowerShell.dll is no where to be found in the 14 ISAPI folder, so I included the full path from the GAC.

As you may know, PowerShell commands consist of a verb followed by a noun such as Get-Command.  The full list of available verbs are listed in the SDK or you can take a look at the System.Management.Automation.VerbsCommon class.  You can choose whichever verb makes since followed by the noun of your choice (assuming it isn’t already taken).  For today’s post, we’re going to look at two different verbs: Get and Set.  The methods you override actually depend on which verb you use.  We’ll start with a simple Hello World cmdlet.  The basis of this cmdlet comes from code I first saw at Ignite.  I’m going to create a new class called SPCmdletHelloWorld.cs.

First, start by adding the necessary references.

using System.Management.Automation;

using Microsoft.SharePoint;

using Microsoft.SharePoint.PowerShell;

The class will inherit from a base class depending on the verb we are implementing.  In this case we are implementing a Get verb so it inherits from SPCmdletBase.  The class takes a generic, so that you can specify the return type.  Keep in mind you can return actual objects such as SPWeb.  It doesn’t have to be primitives.  The class declaration also takes a Cmdlet attribute (I really wish they would have called it Commandlet, but whatever).  This tells PowerShell which verb and noun you are implementing.  In our case, we are implementing Get-SPHelloWorld.  Here is what the declaration looks like.

[Cmdlet(VerbsCommon.Get, "SPHelloWorld")]

public class SPCmdletHelloWorld : SPGetCmdletBase<string>

The next step is to override a method to do our work.  The method you override depends on the particular base class you are overriding from.  In this case, we want to override from RetrieveDataObjects which returns an IEnumerable which I assume has to be the same type as we defined on the class.  In this case we are returning some strings.

protected override IEnumerable<string> RetrieveDataObjects()

{

    return new string[] { "Hello World from DotNetMafia.com!", "This is my first commandlet!" };

}

The whole class together looks like this.

using System;

using System.ComponentModel;

using System.Collections.Generic;

using System.Management.Automation;

using Microsoft.SharePoint;

using Microsoft.SharePoint.PowerShell;

 

namespace DotNetMafia.SharePoint.PowerShell

{

    [Cmdlet(VerbsCommon.Get, "SPHelloWorld")]

    public class SPCmdletHelloWorld : SPGetCmdletBase<string>

    {

        protected override IEnumerable<string> RetrieveDataObjects()

        {

            return new string[] { "Hello World from DotNetMafia.com!", "This is my first cmdlet!" };

        }

    }

}

At this point, we should be able to compile our cmdlet, import it, and be able to execute it.  We don’t have a snapin, but we can still register the code to be executed from PowerShell by using Import-Module.  Specify the full path to the assembly to load it.

Import-Module C:\Code\PowerShell\DemoCmdlet\bin\debug\DotNetMafia.PowerShell.DemoCmdlet.dll

With the module loaded we can execute it using the Get verb.

Get-SPHelloWorld

This will give us results that look like this.

PowerShellCmdletHelloWorld

Now, I’m far from a PowerShell expert, so I had to do some research to figure out what the difference between a PowerShell module and a PowerShell Snapin is.  Both allow you to execute code, but how it is executed varies greatly.  From what I gather though, Snapins are the original way of executing code and in PowerShell 2, modules will be the new way going forward.  This post gives more information on it if you are curious.  There are a few extra steps involved to create a Snapin, but it’s worth seeing, so I’m going to cover them quickly.  I do know that Snapins require admin privileges since you have to put them in the GAC.

First, we need to create a class and inherit from System.Management.Automation.PSSnapin.  I don’t believe it matters what this class is named.  It simply appears to handle the installer logic when you later install the Snappin with GacUtil / InstallUtil (much like a windows service).  In the class we simply override a couple common properties to provide more information about the Snapin.  Here’s what mine looks like.

using System;

using System.ComponentModel;

using System.Management.Automation;

using Microsoft.SharePoint;

using Microsoft.SharePoint.PowerShell;

 

namespace DotNetMafia.PowerShell.DemoCmdlet

{

    [RunInstaller(true)]

    public class DemoPowerShellSnapIn : PSSnapIn

    {

        public override string Name

        {

            get { return "DotNetMafia.PowerShell.DemoCmdlet"; }

        }

 

        public override string Vendor

        {

            get { return "DotNetMafia.com";  }

        }

 

        public override string Description

        {

            get { return "DotNetMafia PowerShell Demo Cmdlet"; }

        }

    }

}

Another file that we may (or may not) have to create is the .psc1 file.  This has the same file prefix as your assembly.  I’m not 100% sure you have to create this (but I have seen it in other sample code), so I’ll show you it just in case.  I do know that you can auto-generate this file using a PowerShell command.

<PSConsoleFile ConsoleSchemaVersion="1.0">

  <PSVersion>1.0</PSVersion>

  <PSSnapIns>

    <PSSnapIn Name="DotNetMafia.PowerShell.DemoCmdlet" />

  </PSSnapIns>

</PSConsoleFile>

The last thing I do is mainly for convenience.  I create a batch file to install my Snapin every time I compile.

@SET GACUTIL="C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\gacutil.exe"

@SET INSTALLUTIL="C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\InstallUtil.exe"

 

%GACUTIL% -if DotNetMafia.PowerShell.DemoCmdlet.dll

%INSTALLUTIL% DotNetMafia.PowerShell.DemoCmdlet.dll

When you compile, you should now see the installer run which looks something like this.

Running a transacted installation.
 
  Beginning the Install phase of the installation.
  See the contents of the log file for the C:\Code\PowerShell\DemoCommandlet\bin\Debug\DotNetMafia.PowerShell.DemoCmdlet.dll assembly's progress.
  The file is located at C:\Code\PowerShell\DemoCommandlet\bin\Debug\DotNetMafia.PowerShell.DemoCmdlet.InstallLog.
  Installing assembly 'C:\Code\PowerShell\DemoCommandlet\bin\Debug\DotNetMafia.PowerShell.DemoCmdlet.dll'.
  Affected parameters are:
     assemblypath = C:\Code\PowerShell\DemoCommandlet\bin\Debug\DotNetMafia.PowerShell.DemoCmdlet.dll
     logfile = C:\Code\PowerShell\DemoCommandlet\bin\Debug\DotNetMafia.PowerShell.DemoCmdlet.InstallLog
     logtoconsole =
 
  The Install phase completed successfully, and the Commit phase is beginning.
  See the contents of the log file for the C:\Code\PowerShell\DemoCommandlet\bin\Debug\DotNetMafia.PowerShell.DemoCmdlet.dll assembly's progress.
  The file is located at C:\Code\PowerShell\DemoCommandlet\bin\Debug\DotNetMafia.PowerShell.DemoCmdlet.InstallLog.
  Committing assembly 'C:\Code\PowerShell\DemoCommandlet\bin\Debug\DotNetMafia.PowerShell.DemoCmdlet.dll'.
  Affected parameters are:
     assemblypath = C:\Code\PowerShell\DemoCommandlet\bin\Debug\DotNetMafia.PowerShell.DemoCmdlet.dll
     logfile = C:\Code\PowerShell\DemoCommandlet\bin\Debug\DotNetMafia.PowerShell.DemoCmdlet.InstallLog
     logtoconsole =
 
  The Commit phase completed successfully.
 
  The transacted install has completed.
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========

If you remember from my first PowerShell post, we register a Snapin with the Add-PSSnapin command.  We can then use Get-Command to inspect which commands are available in the Snappin.  Executing the comamnds is just the same as with the module.  Here is what it looks like.

PowerShellSnapin

You might notice I have two commands listed there.  You can include multiple commands inside one assembly.  Let’s take a look at the second command.  This command actually makes changes inside SharePoint.  It’s a simple command that takes a string and a URL and changes the site title.  This time, we inherit from SPSetCmdletBase<>.  We can treat public fields in our class as command line parameters by using the Parameter attribute.  The position sets the order of the parameters and then you can specify whether they are required or not as well as other options.

[Parameter(Position=0, Mandatory=true)]

public string title;

 

[Parameter(Position=1, Mandatory=true)]

public string url;

Instead of overriding RetrieveDataObjects, we override UpdateDataObject instead.  Then I just use the URL parameter to get an SPWeb object and then update the title. Here’s what the entire class looks like.

using System;

using System.ComponentModel;

using System.Collections.Generic;

using System.Management.Automation;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Administration;

using Microsoft.SharePoint.PowerShell;

 

namespace DotNetMafia.PowerShell.DemoCmdlet

{

    [Cmdlet(VerbsCommon.Set, "SPTitle"), SPCmdlet(RequireUserFarmAdmin = true)]

    public class SPCmdletSetTitle : SPSetCmdletBase<SPWeb>

    {

        [Parameter(Position=0, Mandatory=true)]

        public string title;

 

        [Parameter(Position=1, Mandatory=true)]

        public string url;

 

        protected override void UpdateDataObject()

        {

            using (SPSite siteCollection = new SPSite(url))

            {

                using (SPWeb site = siteCollection.OpenWeb())

                {

                    site.Title = title;

                    site.Update();

                }

            }

        }

    }

}

It looks like this when we execute it.  I’m prompted for parameters since they are mandatory.

PowerShellCmdletSPTitle

When we look at the site now, we can see the changed title.

PowerShellSiteTitleChanged

Hopefully, this is enough to get you started with PowerShell cmdlets.  There is so much more you can do here than what I have mentioned, but this will get you started with two command verbs: Get and Set.  I’ve also attached the code that I have shown to this post.  Enjoy.

Comments

# Twitter Trackbacks for How to: Build a SharePoint 2010 PowerShell Cmdlet - Corey Roth - DotNetMafia.com - Tip of the Day [dotnetmafia.com] on Topsy.com

Pingback from  Twitter Trackbacks for                 How to: Build a SharePoint 2010 PowerShell Cmdlet - Corey Roth - DotNetMafia.com - Tip of the Day         [dotnetmafia.com]        on Topsy.com

# Social comments and analytics for this post

Wednesday, April 28, 2010 10:30 AM by uberVU - social comments

This post was mentioned on Twitter by coreyroth: #SharePoint Post: How to: Build a SharePoint 2010 PowerShell Cmdlet http://bit.ly/b0l6ww

# Liens de la semaine 28/06/2010 : SharePoint 2010, Open XML et standards

Sunday, June 27, 2010 7:01 PM by Julien Chable

Après quelques longues semaines d’absence, voici le retour du post récurrent “Lien de la semaine”. SharePoint

Leave a Comment

(required)
(required)
(optional)
(required)