PowerShell for SharePoint Developers

For some reason, Sharepoint developers haven't taken to PowerShell with the same enthusiasm as the DBAs and SysAdmins. Dave McMohan is a man on a mission to explain that PowerShell can provide plenty of power for repetitive tasks and, once learned, can mean very quick scripting.

As a group, I would say that we .NET and SharePoint Developers are pretty poor generally when it comes to PowerShell. Seeing that it’s ‘command line stuff’, most Developers I know will either turn their noses up at it, or give me the ‘rabbit in the headlights’ look then make a hasty exit, when I suggest they try it. To be fair, I did the same a few months back but, as with all things when faced with the necessity to do something, we normally come up trumps. I’m pleased to report that I’m now relaxed with PowerShell and even take a perverse pleasure in doing things on the command line; Just because I can. If you want this to be you, then read on!

The aim of this article is mainly to get you, a SharePoint Developer, comfortable with the idea of using PowerShell to carry out repetitive tasks. I’ll approach this pretty much as I approached the job of teaching myself; I decided I would learn as much as I needed to know to get by on the particular task I had at hand, and then move on from there.

A secondary aim of this article is to provide you with a few very basic scripts which as a Developer you will probably want to use, and which whilst they are all there out on the great and good Internet, it’s nice to have a little package of useful stuff in one place to refer to from time to time.

By the way, if you want any further motivation to learn PowerShell, don’t forget that STSADM the previous scripting option for SharePoint is deprecated and so there is no guarantee it will be available in future editions. Microsoft are very clear on this, PowerShell is the future of scripting with SharePoint!

The examples I’ve included in this article were all written in the SharePoint 2010 Management Shell which you find at Start -> All Programs -> Microsoft SharePoint 2010 Products.


Looking back on my progress in learning PowerShell, there were just a few things I needed to know to really get going and get productive:

  • Learn how to get PowerShell to run my scripts
  • Learn how to get help
  • Learn how to declare a variable
  • Learn how to Work with Collections
  • Learn how to work with Logical Operators
  • Learn how to use Boolean values

I’m going to go through all these very quickly then as we work through a few examples I’ll add in a few extra bits’ ‘n pieces.

Learn how to get PowerShell to run my scripts

On the face of it this may seem a strange thing to say. PowerShell is a command shell; right? For running scripts; right? So why should I have to do anything to PowerShell to get it to do its primary purpose?

It all comes down to that word which most developers loathe and fear. Security. However, since, by using PowerShell, you can do pretty much anything to both the machine you are on and remote machines too, it’s only common sense to have some safeguards in place which try to protect you from malicious scripts. I’m not going to go into the world of PowerShell Best Practice here. To do things as you should on a production system then I highly recommend you read and implement the instructions in the following Scott Hanselman article. If you want to just play around on your laptop then from the Windows start menu select All Programs -> Microsoft SharePoint 2010 Products -> SharePoint 2010 Management Shell and then type the following:

Contrary to popular belief this will not allow you to run scripts willy-nilly. Each time you run a script which is not “signed” it will prompt you to confirm that you wish to run it. Good enough to my mind for development. If you know 100% that you will not be running any scripts other than your own, you could use Bypass instead of Unrestricted as it disables any prompts and warnings, I’ll leave that decision to you.

So now you know how to actually get PowerShell to run your scripts.

Learn How to Get Help

One thing about PowerShell is its syntax is pretty simple and, thankfully, pretty consistent. If I want to get some help on PowerShell you only have to type the following:

I think even I can remember that.

If I want to get help on a specific SharePoint PowerShell command, say Enable-SPFeature, then I would type:

This then gives me everything I need to know about the command and also how to get to some examples and detailed technical information. Job done.

Learn How to Declare a Variable

As a Developer we’re in the business of working with variables. We’re always assigning and reading variables. It’s something we do best. So how do you do it in PowerShell? We use the $ symbol, thus if I wanted to use a variable called myInt I would refer to it as $myInt. Easy enough and you will be glad to know that PowerShell is case insensitive. So by means of a real example, The first command in the following block assigns a collection of the Service instances to a variable, the second command simply outputs the contents of the $services variable to the console:

Learn how to Work with Collections

Quite often you end up with a collection variable. This happens because although PowerShell is aware of types variables can actually hold any type. So taking our $services variable above, just type a dot ‘.’and then a <tab>. You will see the Count Property show.

If you keep hitting <tab> you will go through all the available properties and methods on the type currently held in the $services variable. The Count is a dead giveaway that you are dealing with a collection variable, if you want further confirmation, keep typing <tab> until you see the GetEnumerator() method.

In the above example with the Get-SPServiceInstance we ended up with a collection variable, but often you only want to go to work on a single object. How to get to the single object?

In this case the syntax is:

This is very C#-ish I think you’ll agree? The Write-Host command simply outputs the result to the console window so that you can see the results which are listed. If you want to do a LINQ type of query where you filter a list with a where clause, you can type the following if you have a single server farm and want to get a reference to the Secure Store Service:

Let’s take a look at this example in a little more detail as it contains the first unique sort of PowerShell syntax and a first real ‘gotcha’ if you are not careful.

First off we have the ‘pipe’ between ‘Get-SPServiceInstance’ and ‘where’. Now most people make a big thing of the ‘pipe’ and indeed it is a very powerful feature. Basically each expression or statement in PowerShell produces an output which can be used as an input to another expression or statement. I’d highly recommend that as you get more familiar with PowerShell you get into the habit of using it. However when you first start out, you will find you don’t need it as much as you might think, and I think that excessive use of the pipe can lead to incomprehensible code for beginners. Think about who is coming after you, not how ‘cool’ your code looks!

Next we have the $_ construct which is the PowerShell way of accessing each element of a collection, an implied loop variable if you like. This essentially allows you to do a trawl through a collection on one line, the collection in this case being the collection of SharePoint Service Instances. So the $_ represents in this case a single SharePoint Service Instance.

Finally, and this is the ‘gotcha’, we have the logical comparison operator ‘-eq’.

Learn how to work with Logical Operators

Why not use the ‘=’ as in VB or ‘==’ sign as in C# for comparison? Well the latter is not valid PowerShell syntax and the former is the assignment operator. See this article for details about the various comparison operators.

So the PowerShell command:

Will error, as ‘==’ is invalid syntax.

Will always return ‘true’ as $s is assigned to the value 4.

Will write ‘true’ to the console only if the value stored in the $s variable is 4. So if you accidentally use the ‘=’ instead of ‘-eq’, you would rename all your SharePoint Service Instances to have a TypeName of ‘Secure Store Service’ if SharePoint allowed that. You can see that in certain circumstances this could have serious consequences! You have been warned!

As an aside, by the way, all the logical operators in PowerShell are preceded with a dash so to do a logical AND you would use ‘-and’, and likewise for OR you would use ‘-or’. Simple enough to remember.

Why did the designers of the language choose -eq as opposed to ==.? I don’t really know, but I’m guessing they assumed that most people who had done scripting on Windows used VB script and were familiar with the ‘=’ sign being the comparison and assignment operator. I’m further assuming they wanted to clearly differentiate between the two in PowerShell, hence the -eq syntax.

Learn how to use Boolean values

Thankfully this is easy enough, as it should be, but a little odd in its syntax. A Boolean value is identified by the terms $true and $false. Note the dollar signs before the words. Don’t ask me why. You can use them just like normal variables which I guess is why they are the way they are. When using them in conjunction with cmdlets they are generally used a little differently though. All PowerShell cmdlets which have side-effects have a “-Confirm” switch which if set to $true prompts the user to confirm they wish to carry out the action. So if I wanted to start up PerformancePoint Service instance I would type something like:

Note the colon after the -Confirm parameter. It won’t work without it, and this is how you set a Boolean switch parameter.

In a similar vein the representation for a Null Reference is $null.

Using PowerShell with SharePoint

So what’s a useful thing to do with PowerShell as a Developer? Well as a developer you need to deploy your SharePoint WSP solution and activate any features which are in those solutions. Now, in your development environment, Visual Studio does all that for you. However, in order to bridge the gap to your production system you can use PowerShell to Add and Install your solution and you can also enable your features. In fact you really can only use PowerShell, or STSADM to add a solution to the Farm Solution Store, so let’s see the PowerShell for each of those:

They’re pretty simple and self-explanatory I hope. I’m assuming your SharePoint Site is at http://sp, your Solution package is called sp.wsp and your feature is called “MyFeature Name”. Obviously change the names to reflect your environment. Note that in PowerShell unlike STSADM, you need to use absolute paths.

You might like to rollback your deployment in which case you need to deactivate your features, uninstall and delete your solution:

Pretty useful. But I suspect you don’t want to have to type all of those lines separately. You’d like to combine them into a script, maybe with parameters which you can run from the command line on a single line. However all our commands so far have relied on using the Microsoft SharePoint 2010 Management Console which through its configuration has pre-loaded the necessary PowerShell library for SharePoint. When we run our scripts, most likely we’ll want to use something like Pre and Post Build command or MSBuild. We need to make sure that PowerShell loads the correct library. Installing SharePoint registers the necessary DLL, but we need to load that DLL into our PowerShell session. So let’s look at another bit standard PowerShell to help us.

The first line is checking to see if the PowerShell is loaded. If you write the above at the command prompt, you will see the >> appear after the closing bracket of the if clause when you hit enter. PowerShell knows when it has an incomplete statement and prompts you with >>. To get out of the multi-line mode, just hit enter twice.

This PowerShell will allow us to run our PowerShell script without having to use the SharePoint 2010 Management Shell, as this script uses the Add-PSSnapin command which adds in the Registered Snapin Microsoft.SharePoint.PowerShell . We can then run our SharePoint PowerShell commands safely from knowing we have access to the relevant libraries.

To complete our first PowerShell for SharePoint script, open up Notepad or Notepad++ or your favourite text editor and type in the following:

Save the file as test.ps1. Now open a standard windows console and type ‘PowerShell’ then enter. This will open the standard windows PowerShell console. Assuming you have a SharePoint farm with the URL http://sp and a solution package called sp.wsp which contains a feature called ‘MyFeature Name”, then to install the feature and enable it type:

To deactivate and uninstall the feature and solution type:

Note that we type “.\test.ps1” and not just “test.ps1”. PowerShell uses fully qualified path names. If you want to do more advanced PowerShell, develop scripts, functions and so forth then I suggest you use PowerGUI. It is a great tool and I highly recommend its use when working with PowerShell. It provides a VS2010 like experience complete with Intellisense and tooltips.


In Summary

Hopefully this brief and rapid introduction to PowerShell for SharePoint has given you a taster to what you can do. My aim has been to get you over those first few hurdles and to get even minimally productive with PowerShell. You should now be able to:

  • Open the SharePoint 2010 Management Console
  • Set Execution Policy
  • Get PowerShell help
  • Assign variables
  • Work with Loops
  • Work with PowerShell logical operators
  • Work with PowerShell Boolean values
  • Create and run a PowerShell Script in any PowerShell window.

I hope this has been of some use and that you now will not run a mile when somebody suggests to you that you should work with PowerShell. Good luck!

1555-ANTS_60x60_Logo_CP.gif How does your SharePoint application perform? The Beta release of ANTS Performance Profiler 8 adds support for SharePoint 2013, helping rapidly identify and understand SharePoint performance issues. Try the Beta.