Welcome!

Release Management Authors: Pat Romanski, Elizabeth White, David H Deans, Liz McMillan, Jnan Dash

Related Topics: Microsoft Cloud, Silverlight

Microsoft Cloud: Blog Feed Post

How to: Build a SharePoint 2010 PowerShell Cmdlet

I’m far from a PowerShell expert, so I had to figure out the difference between a PowerShell module & a PowerShell Snapin

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) is 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.

Read the original blog entry...

More Stories By Corey Roth

Corey Roth, a SharePoint Server MVP, is a consultant at Hitachi Consulting specializing in SharePoint and Office 365 for clients in the energy sector. He has more than ten years of experience delivering solutions in the energy, travel, advertising and consumer electronics verticals.

Corey specializes in delivering ECM and search solutions to clients using SharePoint. Corey has always focused on rapid adoption of new Microsoft technologies including Visual Studio 2013, Office 365, and SharePoint.

He is a member of the .NET Mafia (www.dotnetmafia.com) where he blogs about the latest technology and SharePoint. He is dedicated to the community and speaks regularly at user groups and SharePoint Saturdays.

@ThingsExpo Stories
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
"Digital transformation - what we knew about it in the past has been redefined. Automation is going to play such a huge role in that because the culture, the technology, and the business operations are being shifted now," stated Brian Boeggeman, VP of Alliances & Partnerships at Ayehu, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Synametrics Technologies will exhibit at SYS-CON's 22nd International Cloud Expo®, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Synametrics Technologies is a privately held company based in Plainsboro, New Jersey that has been providing solutions for the developer community since 1997. Based on the success of its initial product offerings such as WinSQL, Xeams, SynaMan and Syncrify, Synametrics continues to create and hone inn...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...