Welcome!

Microsoft Cloud Authors: Janakiram MSV, Yeshim Deniz, David H Deans, Andreas Grabner, Stackify Blog

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
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion 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. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
SYS-CON Events announced today that CAST Software 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. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
SYS-CON Events announced today that Dasher Technologies 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. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of 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. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, 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. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
SYS-CON Events announced today that TidalScale 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. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...
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 ...