Over the past few years I’ve written a number of blog posts on performing various actions against a site collection or web application (display site collection admins, find all SPShell admins with database, find closed web parts). Invariably with every post I get some comments along the lines of “this is great, how can I run this against every site in the farm”. Well today you get your wish (sort of). Below you will find a template script that traverses all sites within your local farm. Isn’t that great!?!
In it’s current state this script will simply output the title and URL of every site within the farm. You may modify the function to perform your desired actions. One stipulation is that you must have proper access to each of the web applications / site collections in order to actually traverse them. Please leave any feedback that you have on this template in the comments.
Scripts
SharePoint 2010
Download the SharePoint 2010 template here.
Here is the source as well
function RecurseSiteAndDoSomething() {
param([Microsoft.SharePoint.SPWeb]$SiteIdentity)
Write-Output "Site: $($SiteIdentity.Url)"
if($SiteIdentity.Webs.Count -gt 0)
{
foreach($subWeb in $SiteIdentity.Webs)
{
RecurseSiteAndDoSomething -SiteIdentity $subWeb
}
}
}
$contentWebAppServices = (Get-SPFarm).services |
? {$_.typename -eq "Microsoft SharePoint Foundation Web Application"}
foreach($webApp in $contentWebAppServices.WebApplications)
{
Write-Output "Web Application: $($webApp.name)"
foreach($siteColl in $webApp.Sites)
{
Write-Output "Site Collection: $($siteColl.Url)"
RecurseSiteAndDoSomething -SiteIdentity $($siteColl.RootWeb)
}
}
SharePoint 2007
I am still ironing out a few things with the SharePoint 2007 version, but here is the current script.
function RecurseSiteAndDoSomething() {
param([Microsoft.SharePoint.SPWeb]$SiteIdentity)
Write-Output "Site: $($SiteIdentity.Url)"
if($SiteIdentity.Webs.Count -gt 0)
{
foreach($subWeb in $SiteIdentity.Webs)
{
RecurseSiteAndDoSomething -SiteIdentity $subWeb
}
}
}
$contentWebAppServices = ([Microsoft.SharePoint.Administration.SPFarm]::Local).services |
? {$_.typename -eq "Microsoft SharePoint Foundation Web Application"}
foreach($webApp in $contentWebAppServices.WebApplications)
{
Write-Output "Web Application: $($webApp.name)"
foreach($siteColl in $webApp.Sites)
{
Write-Output "Site Collection: $($siteColl.Url)"
RecurseSiteAndDoSomething -SiteIdentity $($siteColl.RootWeb)
}
}
Conclusion
In this post I presented a template script for recursively traversing each site within the local SharePoint farm. This is just a first pass at this template. If I make any updates in the future I will update this post to reflect.
-Frog Out
Monday, September 19, 2011 6:28 AM