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
The explosion of new web/cloud/IoT-based applications and the data they generate are transforming our world right before our eyes. In this rush to adopt these new technologies, organizations are often ignoring fundamental questions concerning who owns the data and failing to ask for permission to conduct invasive surveillance of their customers. Organizations that are not transparent about how their systems gather data telemetry without offering shared data ownership risk product rejection, regu...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
@ThingsExpo has been named the Most Influential ‘Smart Cities - IIoT' Account and @BigDataExpo has been named fourteenth by Right Relevance (RR), which provides curated information and intelligence on approximately 50,000 topics. In addition, Right Relevance provides an Insights offering that combines the above Topics and Influencers information with real time conversations to provide actionable intelligence with visualizations to enable decision making. The Insights service is applicable to eve...
SYS-CON Events announced today that Grape Up 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. Grape Up is a software company specializing in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the U.S. and Europe, Grape Up works with a variety of customers from emergi...
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, 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. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
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.
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists will look at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deli...
20th Cloud Expo, taking place June 6-8, 2017, at the Javits Center in New York City, NY, 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 strategy.
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/...
Amazon has gradually rolled out parts of its IoT offerings in the last year, but these are just the tip of the iceberg. In addition to optimizing their back-end AWS offerings, Amazon is laying the ground work to be a major force in IoT – especially in the connected home and office. Amazon is extending its reach by building on its dominant Cloud IoT platform, its Dash Button strategy, recently announced Replenishment Services, the Echo/Alexa voice recognition control platform, the 6-7 strategic...
Bert Loomis was a visionary. This general session will highlight how Bert Loomis and people like him inspire us to build great things with small inventions. In their general session at 19th Cloud Expo, Harold Hannon, Architect at IBM Bluemix, and Michael O'Neill, Strategic Business Development at Nvidia, discussed the accelerating pace of AI development and how IBM Cloud and NVIDIA are partnering to bring AI capabilities to "every day," on-demand. They also reviewed two "free infrastructure" pr...
Judith Hurwitz is president and CEO of Hurwitz & Associates, a Needham, Mass., research and consulting firm focused on emerging technology, including big data, cognitive computing and governance. She is co-author of the book Cognitive Computing and Big Data Analytics, published in 2015. Her Cloud Expo session, "What Is the Business Imperative for Cognitive Computing?" is scheduled for Wednesday, June 8, at 8:40 a.m. In it, she puts cognitive computing into perspective with its value to the busin...
Cognitive Computing is becoming the foundation for a new generation of solutions that have the potential to transform business. Unlike traditional approaches to building solutions, a cognitive computing approach allows the data to help determine the way applications are designed. This contrasts with conventional software development that begins with defining logic based on the current way a business operates. In her session at 18th Cloud Expo, Judith S. Hurwitz, President and CEO of Hurwitz & ...
Financial Technology has become a topic of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 20th Cloud Expo at the Javits Center in New York, June 6-8, 2017, will find fresh new content in a new track called FinTech.
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
The age of Digital Disruption is evolving into the next era – Digital Cohesion, an age in which applications securely self-assemble and deliver predictive services that continuously adapt to user behavior. Information from devices, sensors and applications around us will drive services seamlessly across mobile and fixed devices/infrastructure. This evolution is happening now in software defined services and secure networking. Four key drivers – Performance, Economics, Interoperability and Trust ...
Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the USA and Europe, we work with a variety of customers from emerging startups to Fortune 1000 companies.
Cybersecurity is a critical component of software development in many industries including medical devices. However, code is not always written to be robust or secure from the unknown or the unexpected. This gap can make medical devices susceptible to cybersecurity attacks ranging from compromised personal health information to life-sustaining treatment. In his session at @ThingsExpo, Clark Fortney, Software Engineer at Battelle, will discuss how programming oversight using key methods can incre...
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/...