mandag den 17. december 2012

How to get feature scope using powershell

As i promissed in last post, here is a quick example for a easy way to get the feature scope, when you want to enable a Sharepoint feature.

I added two small functions that can activate a feature based its scope. this way you dont have to specify the feature scope in the script and this way you only need one function for all your features. This function will work fine with my lates post on how to specify all the features in an xml file.

This function takes two parameters: The Identety of the feature, and the URL for a given site. If the url is empty it is set to $null.


-------------------------------------
function ActivateFeature
{    param(
         $Identity,
         $Url = $null
         )
if ($installedFeature = checkFeatureInstalledAndScope -FeatureID $Identity)

{    switch ($installedFeature.Scope)
   {    
    "Farm"
     {
       $feature = (Get-SPFeature -Identity $Identity -Farm
       -erroraction silentlycontinue)
     }        
    "WebApplication"

     {
       $feature = (Get-SPFeature -Identity $Identity -WebApplication $Url
       -erroraction silentlycontinue)
     }
    "Site"
     {
        $feature = (Get-SPFeature -Identity $Identity -Site $Url
        -erroraction silentlycontinue)
     }
    "Web"
     {
        $feature = (Get-SPFeature -Identity $Identity -Web $Url
        -erroraction silentlycontinue)
     }
   }
 
Write-Host "Enabling feature: " $installedFeature.Id "..." -NoNewline

if ($installedFeature.scope -eq "Farm")
{
   Enable-SPFeature -Identity
$Identity

}
else
{
   Enable-SPFeature -Identity
$Identity -Url $Url

}  
Write-Host -ForegroundColor Green "DONE"

function checkFeatureInstalledAndScope
{
 
param(
$FeatureID)

  if ($feature = (get-spfarm).FeatureDefinitions | ?{$_.Id -eq $FeatureID})
  {
    return $feature
  }

  return $null
}

Ingen kommentarer:

Send en kommentar