Welcome!

Release Management Authors: David H Deans, Liz McMillan, Jnan Dash, Lori MacVittie, Gilad Parann-Nissany

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
Everywhere we turn in our industry we can find strong opinions about the direction, type and nature of cloud’s impact on computing and business. Another word that is used in every context in our industry is “hybrid.” In his session at 20th Cloud Expo, Alvaro Gonzalez, Director of Technical, Partner and Field Marketing at Peak 10, will use a combination of a few conceptual props and some research recently commissioned by Peak 10 to offer a real-world consideration of how the various categories of...
Five years ago development was seen as a dead-end career, now it’s anything but – with an explosion in mobile and IoT initiatives increasing the demand for skilled engineers. But apart from having a ready supply of great coders, what constitutes true ‘DevOps Royalty’? It’ll be the ability to craft resilient architectures, supportability, security everywhere across the software lifecycle. In his keynote at @DevOpsSummit at 20th Cloud Expo, Jeffrey Scheaffer, GM and SVP, Continuous Delivery Busine...
SYS-CON Events announced today that Outscale, a global pure play Infrastructure as a Service provider and strategic partner of Dassault Systèmes, will exhibit 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. Founded in 2010, Outscale simplifies infrastructure complexities and boosts the business agility of its customers. Outscale delivers a secure, reliable and industrial strength solution for its customers, which in...
SYS-CON Events announced today that CollabNet, a global leader in enterprise software development, release automation and DevOps solutions, will be a Bronze Sponsor of SYS-CON's 20th International Cloud Expo®, taking place from June 6-8, 2017, at the Javits Center in New York City, NY. CollabNet offers a broad range of solutions with the mission of helping modern organizations deliver quality software at speed. The company’s latest innovation, the DevOps Lifecycle Manager (DLM), supports Value S...
SYS-CON Events announced today that Peak 10, Inc., a national IT infrastructure and cloud services provider, will exhibit 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. Peak 10 provides reliable, tailored data center and network services, cloud and managed services. Its solutions are designed to scale and adapt to customers’ changing business needs, enabling them to lower costs, improve performance and focus intern...
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...
In order to meet the rapidly changing demands of today’s customers, companies are continually forced to redefine their business strategies in order to meet these needs, stay relevant and continue to see profitable growth. IoT deployment and development is integral in this transformation, and today businesses are increasingly seeing the value of investing their resources into IoT deployments. These technologies are able increase ROI through projects such as connecting supply chains or enabling sm...
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, will motivate why realizing the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insigh...
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
SYS-CON Events announced today that Super Micro Computer, Inc., a global leader in compute, storage and networking technologies, will exhibit 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. Supermicro (NASDAQ: SMCI), the leading innovator in high-performance, high-efficiency server technology, is a premier provider of advanced server Building Block Solutions® for Data Center, Cloud Computing, Enterprise IT, Hadoop/...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that EARP Integration will exhibit 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. EARP Integration is a passionate software house. Since its inception in 2009 the company successfully delivers smart solutions for cities and factories that start their digital transformation. EARP provides bespoke solutions like, for example, advanced enterprise portals, business intelligence systems an...
Existing Big Data solutions are mainly focused on the discovery and analysis of data. The solutions are scalable and highly available but tedious when swapping in and swapping out occurs in disarray and thrashing takes place. The resolution for thrashing through machine learning algorithms and support nomenclature is through simple techniques. Organizations that have been collecting large customer data are increasingly seeing the need to use the data for swapping in and out and thrashing occurs ...
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assis...
SYS-CON Events announced today that Progress, a global leader in application development, has been named “Bronze Sponsor” of 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. Enterprises today are rapidly adopting the cloud, while continuing to retain business-critical/sensitive data inside the firewall. This is creating two separate data silos – one inside the firewall and the other outside the firewall. Cloud ISVs oft...
The 21st International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Digital Transformation, 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...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 21st International Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. @ThingsExpo Silicon Valley Call for Papers is now open.
As cloud adoption continues to transform business, today's global enterprises are challenged with managing a growing amount of information living outside of the data center. The rapid adoption of IoT and increasingly mobile workforce are exacerbating the problem. Ensuring secure data sharing and efficient backup poses capacity and bandwidth considerations as well as policy and regulatory compliance issues.
SYS-CON Events announced today that Interoute has been named “Bronze Sponsor” of 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. Interoute is the owner operator of Europe's largest network and a global cloud services platform, which encompasses over 70,000 km of lit fiber, 15 data centers, 17 virtual data centers and 33 colocation centers, with connections to 195 additional partner data centers. Our full-service Unifie...
SYS-CON Events announced today that Progress, a global leader in application development, has been named “Bronze Sponsor” of 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. Enterprises today are rapidly adopting the cloud, while continuing to retain business-critical/sensitive data inside the firewall. This is creating two separate data silos – one inside the firewall and the other outside the firewall. Cloud ISVs ofte...