I’ve often had to write code that iterates through all of the sites in a SharePoint farm. The requirement may be as simple as getting an inventory of sites, or I may need to execute code against each site such as; changing the theme, logo, or activating a feature. Whatever the case may be the logic is simple:
- Get all of the Web Applications
- For each Web Application
- Get all of the Site Collections
- For each Site Collection
- Get all of the Sites (webs)
- For each of the sites (webs)
- Get Site Information or Execute Code (i.e. change theme, logo, master page, activate/deactivate feature)
- Get all of the Sub Sites (webs)
- Repeat step 6
How its done:
Note: Before executing the code make sure that the user executing the logic has the required permissions on every site, or else it wont work. What is the required permission? It depends on what it is you are doing; chances are you’ll be executing this as an admin and should have full control. The following code will iterate through Central Administration and Shared Service Provider Sites, take caution when changing anything on those sites.
Make sure your code references the “Microsoft.SharePoint.Administration” namespace.
Updated 7/22/2008: Added code to handle access denied exceptions at the GetWebs level.
Updated 8/25/2008: Removed recursive call that was causing duplication.