Microsoft SharePoint 2010 and Windows PowerShell 2.0: Expert Cookbook

By Yaroslav Pentsarskyy
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. PowerShell Scripting Methods and Creating Custom Commands

About this book

PowerShell is tightly integrated with SharePoint 2010, demonstrating an important alliance between the fastest growing collaboration and web publishing platform, and the latest task automation framework. The advantages of PowerShell and SharePoint integration help administrators and infrastructure specialists achieve everyday enterprise tasks more efficiently, and this book will ensure you get the most out of SharePoint configuration and management.

When it comes to custom SharePoint 2010 solution configuration, creating robust PowerShell scripts is the best option for saving time and providing a point of reference as to the changes made in the server environment. This practical expert cookbook translates the most commonly found scenarios into a series of immediately usable recipes, allowing you to get up and running straight away with writing powerful PowerShell scripts for SharePoint.

“Microsoft SharePoint 2010 and Windows PowerShell 2.0: Expert Cookbook” focuses on a range of distinct areas of SharePoint administration, with expert recipes targeting unique business examples.
You will learn exactly how solutions were achieved for managing SharePoint list settings with PowerShell, PowerShell configuration of SharePoint FAST Search, and more. You will also learn how to tailor the recipe to your own business needs.

With this advanced cookbook in hand, you will be fully equipped with the source code as a starting point for creating your scripts in order to take advantage of the integration between SharePoint and PowerShell.

Publication date:
November 2011
Publisher
Packt
Pages
310
ISBN
9781849684101

 

Chapter 1. PowerShell Scripting Methods and Creating Custom Commands

In this chapter, we will cover:

  • Setting up your Virtual Machine and running a test script

  • Authoring, debugging, and executing script accessing farm settings with PowerGUI and PowerShell ISE

  • Accessing advanced SharePoint 2010 functionality with external libraries

  • Creating a custom PowerShell command (CmdLet)

  • Creating a custom PowerShell Snap-In

Introduction

PowerShell as a scripting language will execute actions on your target environment. Scripting is not a new concept and PowerShell is definitely not a new language. However, PowerShell and SharePoint 2010 integrate very well. This integration allows administrators and developers to access not just a limited set of commands, but also to connect to SharePoint objects and libraries to take advantage of additional capabilities of SharePoint as a platform. To ensure that we are on the same page while reading this book and trying out various recipes, we'll start by setting up your environment and verifying the setup by running a test script. After all, SharePoint relies on components, most of which we're going to be directly interacting with, and having a consistently configured environment will help in reducing any potential integration issues.

Although we can author our PowerShell scripts in Notepad and execute them in a PowerShell command-line environment, you can experience more advantages from authoring and debugging your scripts by using rich authoring environments, such as PowerGUI or PowerShell ISE. In this chapter, we'll see exactly what the benefits of using those environments are.

Whether you are creating a PowerShell script in a professional scripting environment or calling an existing script from a command line, you'll quickly notice that a default set of commands is definitely not enough to manage and work with your SharePoint system. When you have the need to author scripts accessing various other aspects of SharePoint functionality, you will need to use the additional libraries available to facilitate custom or out-of-the-box functionality required. This is a very common scenario for developers when building custom solutions for a variety of platforms. PowerShell, as a scripting language, really takes advantage of this concept allowing you to call functions from SharePoint and third-party libraries. In this chapter, we'll take a look at exactly how you can access advanced SharePoint 2010 functionality using external libraries.

As you become more familiar with authoring PowerShell scripts, you will realize that you can create a collection of reusable functionality which can be shared with others. That's when you can take advantage of sealing your custom functionality in a portable and sharable way. We'll take a look at how you can package your custom scripts as custom PowerShell CmdLets, as well as how to create a custom PowerShell Snap-In.

 

Introduction


PowerShell as a scripting language will execute actions on your target environment. Scripting is not a new concept and PowerShell is definitely not a new language. However, PowerShell and SharePoint 2010 integrate very well. This integration allows administrators and developers to access not just a limited set of commands, but also to connect to SharePoint objects and libraries to take advantage of additional capabilities of SharePoint as a platform. To ensure that we are on the same page while reading this book and trying out various recipes, we'll start by setting up your environment and verifying the setup by running a test script. After all, SharePoint relies on components, most of which we're going to be directly interacting with, and having a consistently configured environment will help in reducing any potential integration issues.

Although we can author our PowerShell scripts in Notepad and execute them in a PowerShell command-line environment, you can experience more advantages from authoring and debugging your scripts by using rich authoring environments, such as PowerGUI or PowerShell ISE. In this chapter, we'll see exactly what the benefits of using those environments are.

Whether you are creating a PowerShell script in a professional scripting environment or calling an existing script from a command line, you'll quickly notice that a default set of commands is definitely not enough to manage and work with your SharePoint system. When you have the need to author scripts accessing various other aspects of SharePoint functionality, you will need to use the additional libraries available to facilitate custom or out-of-the-box functionality required. This is a very common scenario for developers when building custom solutions for a variety of platforms. PowerShell, as a scripting language, really takes advantage of this concept allowing you to call functions from SharePoint and third-party libraries. In this chapter, we'll take a look at exactly how you can access advanced SharePoint 2010 functionality using external libraries.

As you become more familiar with authoring PowerShell scripts, you will realize that you can create a collection of reusable functionality which can be shared with others. That's when you can take advantage of sealing your custom functionality in a portable and sharable way. We'll take a look at how you can package your custom scripts as custom PowerShell CmdLets, as well as how to create a custom PowerShell Snap-In.

 

Setting up your Virtual Machine and running a test script


In this recipe, we'll ensure your development environment is configured properly.

Getting ready

To complete the recipes in this book, it's assumed you're running a system with SharePoint 2010 Server Standard installed. If not, it is recommended you download and install the 2010 Information Worker Demonstration and Evaluation Virtual Machine (RTM) Virtual Machine environment, if you do not have a compatible system set up. For the most current link to download this virtual environment, search Microsoft Download Center with the keyword 2010 IW demo RTM.

By downloading the preceding environment, you will ensure all of the configurations and setups have been performed and your system is ready for using PowerShell with SharePoint. Whether you're using your own or a downloaded Virtual Machine, let's ensure PowerShell is enabled in your environment.

How to do it...

Let's see how you can get your virtual environment configured and run your first script using the following steps:

  1. 1. On the target Virtual Machine, ensure you are logged in with an administrator's role.

  2. 2. Click Start | All Programs | Microsoft SharePoint 2010 Products | SharePoint 2010 Management Shell.

  3. 3. Input Get-ExecutionPolicy and press Enter on your keyboard. PowerShell may return a value of Restricted.

  4. 4. Input Set-ExecutionPolicy Unrestricted and hit Enter.

    Note

    Ensure this policy is reverted back on your production environments to avoid the risk of malicious script execution.

  5. 5. Input the following command in the window:

    Get-SPSite | Where-Object {$_.Url -eq "http://intranet.contoso.com"}
    
  6. 6. You should see a result that looks similar to the following screenshot:

How it works...

On Windows 2008 Server, PowerShell script execution policy is set to restrict script execution by default. As an administrator, you can choose to allow script execution by calling the Set-ExecutionPolicy Unrestricted command.

Note

For more information on options available for script execution policy and how it affects your environment, search TechNet with the keyword Set-ExecutionPolicy.

Once script execution is not restricted, we run a PowerShell command enumerating all of the SharePoint sites with the http://intranet.contoso.com URL. This assumes you have an existing site collection with such a URL. If you're using the downloadable environment from above, the site collection will be already set up for you. If you're running a site collection with a different URL, feel free to replace the value in this example.

There's more..

In this example, we assumed you were running a Virtual Machine downloaded from the Microsoft download site with all of the pre-set options. In this case, you may see that the execution policy has already been set to unrestricted. In this case, you don't need to set the value again.

 

Authoring, debugging, and executing script accessing farm settings with PowerGUI and PowerShell ISE


As you can see from the previous recipe, authoring and executing a PowerShell script is a simple task that can be done right from the command line. In this recipe, we'll take a look at how you can author and debug your PowerShell scripts using two of the most popular tools: PowerShell ISE and PowerGUI. Using these tools, we'll execute a script accessing farm settings of the SharePoint site.

Getting ready

First, let's ensure you have installed PowerShell ISE:

  1. 1. On the target Virtual Machine, click Start | Administrative Tools | Server Manager.

  2. 2. On the left-hand side panel of the Server Manager window, click the Features node.

  3. 3. In the main window of the Server Manager, click Add Features.

  4. 4. From the Add Features Wizard, ensure Windows PowerShell Integrated Scripting Environment (ISE) is selected. If it is selected and grayed out, as seen in the following screenshot, skip to Step 6 in this sequence.

  5. 5. Click Next and Install on the following window to install the feature.

  6. 6. Upon installation completion, close the Server Manager window.

Let's now install PowerGUI:

  1. 1. Navigate to http://www.powergui.org or search the Internet with PowerGUI.

  2. 2. Download the latest version of PowerGUI installer.

  3. 3. Run the installation package on your development environment and install the PowerGUI tool using the default installation options.

Now that you have all of the tools installed, let's use PowerShell ISE and PowerGUI to author, debug, and execute our new script.

How to do it...

Let's see how PowerShell ISE and PowerGUI can help with your script authoring.

  1. 1. On your development environment, click Start | All Programs | Accessories | Windows PowerShell | Windows PowerShell ISE.

  2. 2. In the PowerShell ISE window's top section, type in the following script:

    $siteUrl = "http://intranet.contoso.com"
    $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
    if ($snapin -eq $null) {
    Write-Host "Loading SharePoint Powershell Snapin"
    Add-PSSnapin "Microsoft.SharePoint.Powershell"
    }
    $site = Get-SPSite | Where-Object {$_.Url -eq $siteUrl}
    $site.WebApplication.QueryFeatures("00BFEA71-EC85-4903-972D-EBE475780106")
    

    Note

    Downloading the example code

    You can download the example code fles for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the fles e-mailed directly to you.

  3. 3. Press F5 on your keyboard.

  4. 4. Take a note of the results returned by the script which will contain multiple instances in the following format:

    DefinitionId : 00bfea71-ec85-4903-972d-ebe475780106
    Parent : My
    Properties : {}
    Definition : SPFeatureDefinition Name=FeatureDefinition/00bfea71-ec85-4903-972d-ebe475780106
    Version : 3.0.0.0
    FeatureDefinitionScope : Farm
    
  5. 5. Now let's see the result with PowerGUI. On your development environment, click Start | All Programs | PowerGUI | PowerGUI Script Editor.

  6. 6. In the top section of the PowerGUI editor, insert the same code we used in step 2 of this sequence:

    $siteUrl = "http://intranet.contoso.com"
    $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
    if ($snapin -eq $null) {
    Write-Host "Loading SharePoint Powershell Snapin"
    Add-PSSnapin "Microsoft.SharePoint.Powershell"
    }
    $site = Get-SPSite | Where-Object {$_.Url -eq $siteUrl}
    $site.WebApplication.QueryFeatures("00BFEA71-EC85-4903-972D-EBE475780106")
    
  7. 7. Press F5 to execute your script.

  8. 8. Take a note of the same result set in the PowerShell Console window right below the editor, seen in the previous image.

  9. 9. Switch back to the script editor section of the screen and set your cursor on the last line of the code.

  10. 10. Press F9 to set the breakpoint on the last line of the code.

  11. 11. Press F5 to execute the script up to the breakpoint.

  12. 12. Take a note of the script editor window when the script has been executed up to the breakpoint. Your PowerGUI editor will look similar to the following screenshot:

  13. 13. At this point you can press F5 on your keyboard to continue execution.

How it works...

We launched the PowerShell ISE to execute our custom script. The first thing our script is going to do is load the PowerShell cmdlet library for SharePoint. This extension library holds various PowerShell functions allowing us to work with SharePoint objects from within PowerShell. Once the library is loaded, our script connects to our SharePoint site, http://intranet.contoso.com, and gets a hold of the current site. Further, the script calls a function which enumerates all of the SharePoint sites and their basic details which have a specified featured ID active in them, as seen in the following screenshot

This function can be pretty handy when you're trying to locate problem features, or determine which site will be affected by the planned feature upgrade.

Our PowerShell script has been executed first in PowerShell ISE to see what capabilities you have in this Integrated Scripting Environment (ISE).

We then used PowerGUI to see how the same script can be executed and debugged. As you can see, PowerGUI has a few more features facilitating the script authoring process.

The debug option available in the script editor is particularly handy when your script doesn't quite yet work to your standards, and you want to figure out potential problems in it. If you're a developer, you already know all about debugging and its benefits.

Once you're satisfied with the script, you can execute it and run it on the current environment.

There's more

Let's take a look at how we can author and execute scripts with PowerGUI.

Script authoring with PowerGUI

One of the other advantages to PowerGUI is the ability to see values of variables in your script as it executes. The Variables panel is, by default, on the right-hand side of your PowerGUI window as seen here:

Without this panel, if you wanted to list the variable value, you would typically need to call it in a command line. If the variables in question are complex objects, you get to see the value of all the properties too, as shown in the following screenshot:

Also, to aid you with script authoring, PowerGUI has a collection of handy snippets which you can access with the Edit | Insert Snippet option.

Note

For more tips on working with PowerGUI user interface and features, check out http://www.Powergui.org. For more tips on PowerShell ISE, search TechNet for Windows PowerShell Integrated Scripting Environment.

 

Accessing advanced SharePoint 2010 functionality with external libraries


In the previous recipe, we looked at some of the functionalities available to you in the PowerShell library, designed to help you access basic features in SharePoint. By using those features, you can access SharePoint objects and manipulate their properties. But what if you need to access the object model beyond what's available to you from the PowerShell snap-in for SharePoint? In this recipe, we'll take a look at how you can access more advanced features in SharePoint by referencing SharePoint assemblies and associated methods in those libraries.

Getting ready

In this example, we'll be using PowerGUI to execute our script. So log in to your environment with administrative privileges and launch PowerGUI.

How to do it...

The following steps will demonstrate how you can use some of the advanced SharePoint functions by referencing external assemblies in your PowerShell script:

  1. 1. Navigate to the test site URL: http://intranet.contoso.com and click on the Shared Documents library to access the library.

  2. 2. In the ribbon click Library | Library Settings.

  3. 3. Under Permissions and Management click Information management policy settings as seen in the following screenshot:.

  4. 4. Select Document from the list of available content types.

  5. 5. Take note that none of the policies have been defined for this document library.

  6. 6. Switch to your PowerGUI scripting editor and enter the following script:

    $siteUrl = "http://intranet.contoso.com"
    $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
    $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
    if ($snapin -eq $null) {
    Write-Host "Loading SharePoint Powershell Snapin"
    Add-PSSnapin "Microsoft.SharePoint.Powershell"
    }
    $site = Get-SPSite | Where-Object {$_.Url -eq $siteUrl}
    $web = $site.OpenWeb();
    $list = $web.Lists["Shared Documents"];
    $policy = [Microsoft.Office.RecordsManagement.InformationPolicy.ListPolicySettings]($list);
    if ($policy.ListHasPolicy -eq 0)
    {
    $policy.UseListPolicy = "true";
    $policy.Update();
    }
    $contentType = $list.ContentTypes["Document"];
    [Microsoft.Office.RecordsManagement.InformationPolicy.Policy]::CreatePolicy($contentType, $null);
    $newPolicy = [Microsoft.Office.RecordsManagement.InformationPolicy.Policy]::GetPolicy($contentType);
    $newPolicy.Items.Add(
    "Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration",
    "<Schedules nextStageId='3'>" +
    "<Schedule type='Default'>" +
    "<stages>" +
    "<data stageId='1' stageDeleted='true'></data>" +
    "<data stageId='2'>" +
    "<formula id='Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration.Formula.BuiltIn'>" +
    "<number>1</number>" +
    "<property>Created</property>" +
    "<period>years</period>" +
    "</formula>" +
    "<action type='action' id='Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration.Action.MoveToRecycleBin' />" +
    "</data>" +
    "</stages>" +
    "</Schedule>" +
    "</Schedules>");
    $newPolicy.Update();
    
  7. 7. Press F5 to execute the script, and then wait until the script executes.

  8. 8. Switch back to the policy setting page we accessed in step 5. Take note of the new policy added to the Retention policy where expiration has been enabled on the document library items, as seen in the following screenshot:

How it works...

The preceding code demonstrates how to take advantage of SharePoint class libraries to access functionality and methods available in those class libraries, and not directly available as PowerShell SharePoint script extensions. Although methods used here are discussed in detail in Chapter 8, Managing Documents and Records in SharePoint with PowerShell, this recipe demonstrates basics behind accessing SharePoint object model using PowerShell. In this example, we created a new expiration policy on the document library of the team site on the development environment downloaded from Microsoft's download site http://intranet.contoso.com.

We started by accessing the site which we are interested in by using the PowerShell Get-SPSite method. We then accessed the current site at which the SharePoint Documents document library is hosted.

Next, we got hold of the current policy on the library in order to add a new instance of a policy.

We used the CreatePolicy method available in the [Microsoft.Office.RecordsManagement.InformationPolicy.Policy] namespace to create a policy for the library. This part demonstrates how the function is not available in the PowerShell syntax, but is available in the SharePoint library, and can be called in order to access some of the advanced functions in SharePoint.

The rest of the preceding code adds the definition of the policy we're trying to create on the library and adds the new policy object to the list of available policies.

When you execute this script, the newly defined policy will be added to the library on the site.

There's more

Let's take a look at how you can access external SharePoint libraries to execute more advanced PowerShell commands.

Accessing other SharePoint libraries and related functions

In this example, we looked at how you can create an expiration formula on the library, but there is plenty more you can do. To access functions in SharePoint libraries, you need to identify the object class and namespace those functions belong to so you can reference them in PowerShell.

If you search for the policy function class on TechNet you will find: Microsoft.Office.RecordsManagement.InformationPolicy.Policy. From there you can also determine various functions available to be called.

To call any of the functions, you would use the method we used in the preceding source code and reference the namespace first, followed by the class and function names.

Let's look at another example where we use PowerShell to connect to the current site and then change the status of features on the site.

  1. 1. Open PowerGUI, click File | New to create a new script.

  2. 2. Add the following code to the script window:

    $siteUrl = "http://intranet.contoso.com"
    $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
    if ($snapin -eq $null) {
    Write-Host "Loading SharePoint Powershell Snapin"
    Add-PSSnapin "Microsoft.SharePoint.Powershell"
    }
    $site = Get-SPSite | Where-Object {$_.Url -eq $siteUrl}
    $features = $site.FeatureDefinitions;
    $features.get_Item("CustomFeature").Status = "Offline"
    
  3. 3. Run the script from within PowerGUI by pressing F5.

  4. 4. Verify the status of our CustomFeature which should be Offline.

Note that we did not have direct access to the features object but rather to its parent. Yet, by using PowerShell, we were able to call function on a child object allowing us to change the status of the feature on the site.

In this case, we set the feature to be Offline. Among other available options related to a feature status, we could choose the following: Online, Disabled, Offline, Unprovisioning, Provisioning, Upgrading.

As you can see, this method is handy when you need to disable defective features across many sites in your environment.

This example demonstrates how you can access other available libraries in SharePoint and even your own custom libraries to call functions from within them.

 

Creating a custom PowerShell command (CmdLet)


In this chapter, previous recipes have tackled accessing custom functions in other SharePoint libraries, and using those functions to perform various operations in our script. It's now time for us to see how we can create our own custom function executing some custom logic. Once the command has been created, it will be accessible from within PowerShell for users to call.

This is particularly handy when you're creating a collection of functions which perform frequent administrative tasks on your server.

Another example where you might want to create your own CmdLet is when you're planning to package those as custom offering for your customers to download and use on their environments.

Getting ready

To create a custom CmdLet, we will be using Visual Studio 2010 Professional. If you're using the virtualized environment we downloaded in the recipe, Setting up your Virtual Machine and running a test script, Visual Studio 2010 Professional will already be installed on your system. Otherwise, ensure you at least have the Professional version installed to continue with this recipe.

How to do it...

Let's take a look at how you can create your own CmdLet using the following steps:

  1. 1. From within your Visio Studio 2010, click File | New | Project ….

  2. 2. From Installed Templates select Visual C# | Class Library.

  3. 3. Leave the default name for the project as ClassLibrary1 and click OK.

  4. 4. In the Solution Explorer, right-click References | Add Reference to add the following references:

    System.Management.Automation, which can be found in a list of assemblies in the .NET

  5. 5. Also add a reference to Microsoft.SharePoint. The reference can be found in the SharePoint tab as seen here:

  6. 6. In the Solution Explorer, pick the Class1.cs and rename the file to PowerShell Cmdlet1.cs.

  7. 7. Replace the contents of the PowerShell Cmdlet1.cs with the following code:

    using System.Management.Automation;
    using Microsoft.SharePoint;
    namespace PowerShellCmdlet1
    {
    [Cmdlet(VerbsCommon.Set, "WebTitle")]
    public class PowerShell_Cmdlet1 : Cmdlet
    {
    [Parameter()]
    public string siteUrl;
    [Parameter()]
    public string newTitle;
    protected override void ProcessRecord()
    {
    base.ProcessRecord();
    using (SPSite site = new SPSite(siteUrl))
    {
    using (SPWeb web = site.OpenWeb())
    {
    web.Title = newTitle;
    web.Update();
    WriteObject("New Title: " + web.Title);
    }
    }
    }
    }
    }
    
  8. 8. Right-click the project name ClassLibrary1 and select Properties.

  9. 9. From the Properties page, pick the Signing tab and check the check mark titled Sign the assembly.

  10. 10. From the drop-down entitled Choose a strong name key file, pick New and provide key filename of your choice, which usually is safe to call key.snk.

  11. 11. Uncheck Protect my file with a password and click OK.

  12. 12. Your project will now have an assigned key as shown in the following screenshot:

  13. 13. At this point, your Visual Studio Solution Explorer tree will look as in the following screenshot:

How it works...

At this stage, we have created a new class representing our CmdLet with Visual Studio solution. Visual Studio will produce an assembly file as an output of the solution once built.

Our solution has only one CmdLet functionality which is defined in PowerShell_Cmdlet1. You will notice the [Cmdlet(VerbsCommon.Set, "WebTitle")] part of the code defines the type of the command and the name of it.

Note

If you noticed, all of the PowerShell commands we have called so far have a naming convention of a [Verb]-[Action]. The verb in this case is either Get or Set. In fact, for the full list of available verbs, in your command let code, place the cursor over VerbsCommon.Set and press F12. Visual Studio will display all of the available verbs allowing you to find the one appropriate to the CmdLet you're creating.

The second part of the CmdLet declaration is the action of your function, which can be titled according to your preference.

Note

The best practice here is to name the command something descriptive to the action executed by it.

The actual functionality of the CmdLet is defined right below the CmdLet declaration, in our case, in the PowerShell_Cmdlet1 class.

We started with a parameter declaration, which is an optional piece but often used. Since most PowerShell commands contain a reusable set of instructions to be performed on the object, it's very common when authoring a new script to accept parameters specifying an object. For PowerShell scripts interacting with SharePoint, this will be a URL of the site or list name, and so on. In our case, we'll capture the URL and the new title of the SharePoint site. The following function will use the parameters we supplied to connect to the URL we have identified, and rename the site title to the one defined.

The logic defined in ProcessRecord of our code handles all of the functionality our CmdLet will execute, and this is where you can code the functionality of your own CmdLet.

Finally, once the logic of our CmdLet has been created, we're prepared to make the functionality available in the PowerShell command line. Details of the CmdLet installation process are described in the Creating a custom PowerShell Snap-In recipe.

Due to the nature of CmdLet, before installing it on the system, we need to make sure the output DLL is signed with a strong name.

The purpose of signing the assembly with the strong name is to ensure the assembly can be dropped into the Global Assembly Cache (GAC), where it can be consumed by the installation process.

See also

Creating a custom PowerShell Snap-In recipe in this chapter.

 

Creating a custom PowerShell Snap-In


As we've seen in the Creating a custom PowerShell command (CmdLet) recipe, the creation of PowerShell CmdLet is a process of defining the functionality you want to expose to the user, and sealing it as a .NET assembly. In this recipe, we'll take a look at how you install your custom CmdLet which directly involves the creation of a PowerShell Snap-In.

We have already used the PowerShell Snap-In when we referenced a set of SharePoint Set earlier in this chapter. In this case, we called the following command:

Add-PSSnapin "Microsoft.SharePoint.Powershell"

In this example, we'll use similar approach to call our custom Snap-In.

Getting ready

As trivial as it sounds, to create a Snap-In, you will need to create another class in the Visual Studio solution you created earlier to define your CmdLet. Your Snap-In solution doesn't need to contain both a Snap-In and a CmdLet. In fact, you can have them created in two separate solutions as long as your Snap-In references the CmdLet. In this example we'll add a Snap-In class to the existing CmdLet solution, which is very common when creating PowerShell CmdLet libraries.

How to do it...

We'll take a look at how you can create your own PowerShell Snap-In.

  1. 1. Switch to the Visual Studio 2010 solution you used to create a CmdLet earlier.

  2. 2. From the Solution Explorer, right-click the project name, PowerShellCmdlet1 and select Add | Class ….

  3. 3. In the Solution Explorer, pick the Class1.cs and rename the file to PowerShell Cmdlet1.cs

  4. 4. Rename the newly created class to PowerShellCmdlet SnapIn1.cs.

  5. 5. Open the class file created and replace the contents of the PowerShellCmdlet SnapIn1.cs with the following code:

    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    namespace PowerShellCmdlet1
    {
    [RunInstaller(true)]
    public class PowerShellCmdlet_SnapIn1 : CustomPSSnapIn
    {
    private Collection<CmdletConfigurationEntry> _cmdlets;
    /// <summary>
    /// The description of powershell snap-in.
    /// </summary>
    public override string Description
    {
    get { return "A Description of MyCmdlet"; }
    }
    /// <summary>
    /// The name of power shell snap-in
    /// </summary>
    public override string Name
    {
    get { return "MyCmdlet"; }
    }
    /// <summary>
    /// The name of the vendor
    /// </summary>
    public override string Vendor
    {
    get { return ""; }
    }
    public override Collection<CmdletConfigurationEntry> Cmdlets
    {
    get
    PowerShell Snap-Increating, steps{
    if (null == _cmdlets)
    {
    _cmdlets = new Collection<Cmdlet ConfigurationEntry>();
    _cmdlets.Add(new CmdletConfigurationEntry
    ("Set-WebTitle", typeof(PowerShell_Cmdlet1), "Set-WebTitle.dll-Help.xml"));
    }
    return _cmdlets;
    }
    }
    }
    }
    
  6. 6. Right-click the project name PowerShellCmdlet1 and select Build.

  7. 7. Right-click the project name PowerShellCmdlet1 and select Open Folder in Windows Explorer.

  8. 8. In the folder opened, open the bin\Debug folder and locate the PowerShellCmdlet1.dll.

  9. 9. Click Start | Run on your development environment and open the Global Assembly Cache by typing c:\windows\assembly.

  10. 10. Drag-and-drop the PowerShellCmdlet1.dll to the assembly folder.

  11. 11. Open a PowerShell command line from Start | All Programs | Accessories | Windows PowerShell | Windows PowerShell.

  12. 12. Type in the following command to install our newly added Snap-In assembly. Ensure the path to your assembly is correct. In this example, our path is C:\Users\Administrator\Documents\visual studio 2010\projects\PowerShellCmdlet1\PowerShellCmdlet1\bin\Debug:

    PS> set-alias installutil $env:windir\Microsoft.NET\Framework\v2.0.50727\installutil
    PS> cd "C:\Users\Administrator\Documents\visual studio 2010\projects\PowerShellCmdlet1\PowerShellCmdlet1\bin\Debug"
    S> installutil PowerShellCmdlet1.dll
    
  13. 13. Now that our Snap-In has been installed, let's open our SharePoint test intranet site, http://intranet.contoso.com. Take note of the current site title.

  14. 14. Switch back to the PowerShell command-line window and register the new Snap-In:

    PS> Add-PSSnapin "MyCmdlet"
    
  15. 15. Let's change the title of the site by executing our custom CmdLet:

    PS> Set-WebTitle -siteUrl "http://intranet.contoso.com" -newTitle "Test Title"
    
  16. 16. Switch back to http://intranet.contoso.com and take note of the changed title.

How it works...

Since we have already created the actual CmdLet, we reused the same Visual Studio solution to add a Snap-In class. The Snap-In class will perform the role of installer. As you can see, the contents of the class declare the name and description on the CmdLet as well as a reference to CmdLet class. This information will further be used to identify your custom CmdLet.

Once the solution has been built and the solution library has been generated, we copied the library to GAC. We used InstallUtil to install and uninstall server resources by executing the installer components in our CmdLet library. By executing the InstallUtil command we will actually make the Snap-In available in the PowerShell command line.

Once installed, we can add the Snap-In and execute our custom CmdLet.

As you will notice, due to the fact that our custom Snap-In library will be placed into the GAC, the custom code executed will have access to most of the server resources. Because of the level of access, when downloading custom Snap-Ins ensure they come from a trusted source.

There's more

Let's take a look at how you can uninstall your Snap-In from the system as well as how Visual Studio templates can help you with Snap-In authoring.

Uninstalling a Snap-In from your system

Previously, we looked at how you can install the Snap-In so it's available to be called from the command line. You can also uninstall the Snap-In by using the uninstall key of the InstallUtil command. Here is a sample uninstall syntax for our Snap-In:

PS> installutil /u PowerShellCmdlet1.dll

It's quite common to need to uninstall the Snap-In. One common scenario includes the CmdLet authoring process. As you author your CmdLet and discover problems with it or would like to add more functionality, to have the new version available you would need to re-install the Snap-in on the environment.

Visual Studio CmdLet and Snap-In item templates

In this example, we looked at how you can install a custom PowerShell Snap-In by adding code to a Visual Studio solution. Since this is a fairly common task, there are a few templates available online which you're welcome to use to create core CmdLet and Snap-In code automatically. The core functionality will be your starting point which you can add your customizations to.

One of the templates you can try is available at CodePlex. The project is called PowerShell Visual Studio 2008 templates and recently was hosted at this URL: http://psvs2008.codeplex.com.

Although the version of this package is specifically designed for Visual Studio 2008, it is also compatible with Visual Studio 2010.

Once you download the package, open it on the development environment where you have Visual Studio installed, and install all of the suggested components, as seen in the following screenshot:

Once installed, to add a new instance of a template for CmdLet and Snap-In, simply right-click on the project name in Solution Explorer, and select Add | New Item.

From here, you need to pick the appropriate Snap-In or CmdLet template and click Add to create an initial version of the file, as seen in the following screenshot:.

Whether you will be using components from the preceding template, or creating your own CmdLet classes, search MSDN with the keyword Cmdlet Development Guidelines for some handy tips and details on authoring your CmdLets.

About the Author

  • Yaroslav Pentsarskyy

    Yaroslav Pentsarskyy has been involved in SharePoint solution architecture and implementation since 2003. As a Microsoft MVP since 2009 he keeps in close touch with the SharePoint product team. Yaroslav frequently presents at local and worldwide tech events as well as online; you can always find a fresh bit of SharePoint information on his blog: http://www.sharemuch.com. He is the author of two other SharePoint titles: “Top 60 custom solutions built on SharePoint 2010” and “SharePoint 2010 branding in practice”. Yaroslav Pentsarskyy is the author of "Microsoft SharePoint 2010 and Windows PowerShell 2.0: Expert Cookbook".

    Browse publications by this author
Book Title
Unlock this book and the full library for FREE
Start free trial