Saturday, January 22, 2011

Enumerate site collections, subsites and activate feature using Power Shell

This script enumerates through all site collections for a given web application, then enumerates through all subsites within each site collection and activates the given web level feature, copy the script as mentioned below, change the highlighted sections and save it as IterateSiteSubsitesActivateWebLevelFeature.ps1 file:

 Powershell Script updated on Feb 10th, 2012.

Add-PsSnapin Microsoft.SharePoint.PowerShell

## SharePoint DLL
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$webApplicationURL = "http://dev-sp-2010:1000"
$featureFolderName = "PublishingWeb"

$webApp = Get-SPWebApplication $webApplicationURL

if($webApp -ne $null)
{
foreach($siteColl in $webApp.Sites)
{
   if($siteColl -ne $null)
   {
foreach($subWeb in $siteColl.AllWebs)
{
if($subWeb -ne $null)
{
# Print each Subsite
#Write-Host $subWeb.Url
                 
#Get Feature ID based on the Feature Name
$FeatureID = Get-SPFeature -Web $subWeb.Url | Where {$_.DisplayName -eq $featureFolderName}

if($FeatureID -ne $null)
{
#Check whether Feature to be activated is already activated for this subsite
if (Get-SPFeature -Web $subWeb.Url | Where {$_.ID -eq $FeatureID.Id})
{
Write-Host $featureFolderName "is already activated at :" $subWeb.Url
   }
else
{
#Enable-SPFeature -Identity $featureFolderName -Confirm:$false -Url $subWeb.url
Write-Host $featureFolderName "has been activated at :" $subWeb.url
}
}
$subWeb.Dispose()
}
else
{
Echo $subWeb "does not exist"
}
}
$siteColl.Dispose()
}
else
{
Echo $siteColl "does not exist"
}
}
}
else
{
Echo $webApplicationURL "does not exist, check the WebApplication name"
}

Remove-PsSnapin Microsoft.SharePoint.PowerShell

Echo Finish

 
To automatically run this script as a batch utility, use the following:
Copy code below, save it as a .bat file to run the powershell script

cd /d %~dp0
powershell -noexit -file ".\IterateSiteSubsitesActivateWebLevelFeature.ps1" "%CD%"
pause

I hope this helps. Also refer to the Microsoft TechNet post for an alternative webservice approach: http://blogs.msdn.com/b/vijay/archive/2009/10/01/how-to-list-all-the-sub-sites-and-the-site-collections-within-a-sharepoint-web-application-using-windows-powershell.aspx