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.

 1function Get-SPFeatureActivations() {
 2  <#
 3  .Synopsis
 4    Retrieves Feature activations for the given Feature Definition.
 5  .Description
 6    Retrieves the SPFeature object for each activation of the SPFeatureDefinition object.
 7  .Example
 8    Get-SPFeatureActivations TeamCollab
 9  .Parameter Identity
10    The Feature name, ID, or SPFeatureDefinition object whose activations will be retrieved.
11  .Parameter NeedsUpgrade
12    If specified, only Feature activations needing upgrading will be retrieved.
13  .Link
14    Get-SPFeature
15  #>
16  [CmdletBinding()]
17  param (
18    [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
19    [Alias("Feature")]
20    [ValidateNotNullOrEmpty()]
21    [Microsoft.SharePoint.PowerShell.SPFeatureDefinitionPipeBind]$Identity,
22    
23    [Parameter(Mandatory=$false, Position=1)]
24    [switch]$NeedsUpgrade
25  )
26  begin { }
27  process {
28    $fd = $Identity.Read()
29    switch ($fd.Scope) {
30      "Farm" {
31        [Microsoft.SharePoint.Administration.SPWebService]::AdministrationService.QueryFeatures($fd.ID, $NeedsUpgrade.IsPresent)
32        break
33      }
34      "WebApplication" {
35        [Microsoft.SharePoint.Administration.SPWebService]::QueryFeaturesInAllWebServices($fd.ID, $NeedsUpgrade.IsPresent)
36        break
37      }
38      "Site" {
39        foreach ($webApp in Get-SPWebApplication) {
40          $webApp.QueryFeatures($fd.ID, $NeedsUpgrade.IsPresent)
41        }
42        break
43      }
44      "Web" {
45        foreach ($site in Get-SPSite -Limit All) {
46          $site.QueryFeatures($fd.ID, $NeedsUpgrade.IsPresent)
47          $site.Dispose()
48        }
49        break
50      }
51    }
52  }
53  end { }
54}

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):

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:

1Get-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):

1Get-SPFeatureActivations MyCustomFeature | ForEach-Object {
2  Enable-SPFeature -Identity MyCustomFeature -Url $_.Parent.Url -Force
3}

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

1Get-SPFeatureActivations MyCustomFeature -NeedsUpgrade | ForEach-Object {
2  $_.Upgrade($false)
3}

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