Retrieving SharePoint 2010 Feature Activations Using Windows PowerShell

Posted on Posted in PowerShell Scripting, Scripts

During my PowerShell for Developers presentation in London last week I promised to show and demonstrate a script for retrieving Feature activations; unfortunately I ran out of time and was not able to show this script to the degree that I’d intended so I decided to throw together this blog post.

When developing custom Features it is very common to expect that there will need to be some level of update required for those Features. Typically this means that, after deploying the Feature via a Solution Package, you will need to re-activate that Feature in order to trigger any additional code to run (or, if you are using the new SharePoint 2010 Feature upgrade capabilities you will need to run the Upgrade(Boolean) method of the SPFeature object). The problem is knowing where the Feature is activated throughout the Farm. Using PowerShell there are two ways to do this – you can use the Get-SPFeature cmdlet and test the results against the appropriate scope or you can use the various “Query” methods that have been provided for each scope. I don’t recommend that you use the Get-SPFeature cmdlet as it is very inefficient, and as such, I won’t bother showing an example of that here. Instead I’ll focus on the “Query” methods approach.

Whether your Feature is scoped to the Farm, Web Application, Site Collection, or Site, there is a method that you can call to get an SPFeature object which effectively corresponds to a Feature activation. For Farm scoped Features you use the QueryFeatures(Guid, Boolean) method of the SPWebService class, obtainable via the SPWebService class’ static AdministrationService property; for Web Application scoped Features you use the static QueryFeaturesInAllWebServices(Guid, Boolean) method of the SPWebService class; for Site Collection scoped Features you use the QueryFeatures(Guid, Boolean) method of the SPWebApplication class; and for Site scoped Features you use the QueryFeatures(Guid, Boolean) method of the SPSite class.

To create our PowerShell function we’ll simply take in a SPFeatureDefinition object and use a switch statement to call the appropriate method based on the scope of the Feature. To make the function more versatile we can use the Microsoft.SharePoint.PowerShell.SPFeatureDefinitionPipeBind type which will allow the caller to pass in either the name of the Feature, its ID, or an actual SPFeatureDefinition object; additionally, we can use parameter attributes to easily allow the value to be passed in via the object pipeline. And finally, we’ll add an additional parameter stating that we wish to retrieve only those activations that require upgrading and we’ll add some basic help for the function.

The following code listing represents the completed function – I recommend that you save this to a file named Get-SPFeatureActivations.ps1. Note that I plan on adding this as a cmdlet to my downloadable extensions thereby making the need for this script unnecessary, however, I believe that this example provides a great template to use for creating professional looking, production ready scripts that both IT administrators and developers can use.

function Get-SPFeatureActivations() {
  <#
  .Synopsis
    Retrieves Feature activations for the given Feature Definition.
  .Description
    Retrieves the SPFeature object for each activation of the SPFeatureDefinition object.
  .Example
    Get-SPFeatureActivations TeamCollab
  .Parameter Identity
    The Feature name, ID, or SPFeatureDefinition object whose activations will be retrieved.
  .Parameter NeedsUpgrade
    If specified, only Feature activations needing upgrading will be retrieved.
  .Link
    Get-SPFeature
  #>
  [CmdletBinding()]
  param (
    [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
    [Alias("Feature")]
    [ValidateNotNullOrEmpty()]
    [Microsoft.SharePoint.PowerShell.SPFeatureDefinitionPipeBind]$Identity,
    
    [Parameter(Mandatory=$false, Position=1)]
    [switch]$NeedsUpgrade
  )
  begin { }
  process {
    $fd = $Identity.Read()
    switch ($fd.Scope) {
      "Farm" {
        [Microsoft.SharePoint.Administration.SPWebService]::AdministrationService.QueryFeatures($fd.ID, $NeedsUpgrade.IsPresent)
        break
      }
      "WebApplication" {
        [Microsoft.SharePoint.Administration.SPWebService]::QueryFeaturesInAllWebServices($fd.ID, $NeedsUpgrade.IsPresent)
        break
      }
      "Site" {
        foreach ($webApp in Get-SPWebApplication) {
          $webApp.QueryFeatures($fd.ID, $NeedsUpgrade.IsPresent)
        }
        break
      }
      "Web" {
        foreach ($site in Get-SPSite -Limit All) {
          $site.QueryFeatures($fd.ID, $NeedsUpgrade.IsPresent)
          $site.Dispose()
        }
        break
      }
    }
  }
  end { }
}

Assuming you’ve saved the file to the root of the C drive (not recommended but its what I do when I’m doing demos) then you can load the function into memory using dot sourcing as shown in the following example (note that the help for the function shows the help information specified by the block comment help):

SNAGHTML45555695

Once the function is loaded into memory you can start using it. In the following example I’m returning back all the locations where the MyCustomFeature Feature is activated; I then use the Select-Object cmdlet to return just the URL for each activation:

Get-SPFeatureActivations MyCustomFeature | select @{Expression={$_.Parent.Url};Label="Url"}

In this next example, instead of simply outputting the URL of each activation, I’m forcing the Feature to be reactivated using the Enable-SPFeature cmdlet (use the -Force parameter to force the Feature to be reactivated – you could also change the code to deactivate the Feature using the Disable-SPFeature cmdlet and then activate using the Enable-SPFeature cmdlet):

Get-SPFeatureActivations MyCustomFeature | ForEach-Object {

  Enable-SPFeature -Identity MyCustomFeature -Url $_.Parent.Url -Force

}

Similarly you can retrieve only those Features needing upgrade and then call the Upgrade() method, as shown in this next example:

Get-SPFeatureActivations MyCustomFeature -NeedsUpgrade | ForEach-Object {

  $_.Upgrade($false
)

}

I strongly recommend that, before you re-deploy a Feature that may be activated at an unknown number of scopes, you run this function (or something similar to it) so that you fully understand the impact of upgrading your Feature. One more thing to watch out for, if your environment is very large you may wish to modify this function so that it does not return the SPFeature object but instead just returns the URL corresponding to the activation – you can then use the Get-SPFeature cmdlet to retrieve the SPFeature object; the benefit of this is that you can immediately dispose of the parent object and prevent potential out of memory errors (I’m particularly concerned with Site Collection and Site scoped Features here where the Parent property of the SPFeature object corresponds to an SPSite or SPWeb object which must be disposed).

That’s all I’ve got for now; hopefully you’ve found this useful!

-Gary

3 thoughts on “Retrieving SharePoint 2010 Feature Activations Using Windows PowerShell

  1. Gary, thank you for this, it’s is great. And it really shows the power that can be achieved from some apparently simple PowerShell constructs.

    One small glitch that I have noticed though… for Site-scoped features, it errors (E_ACCESSDENIED) if the feature is active on a site to which you do not have access.

    Not really a bug in your code, as it’s just Sharepoint’s habit of denying permissions by default. An obvious workaround would be to run the function as a user that has the Full Read policy on all the web applications in the farm. But a) I haven’t tried that yet, and b) I can almost hear the cries of anguish from more cautious organisations…

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA

*