March 8, 2013

SharePoint 2010: Iterate all webs in Web Application

Sometimes you're just there and need to do something with all of your SPWebs, but have the unfortunate structure of having http://Portal/Sites/SiteCollections in your architecture. There is a way out which is quite simple and working very well. All you need to do is to get hold of all the SiteCollections (SPSite) in the WebApplication (http://portal).


$SPWebApp = Get-SPWebApplication "http://portal/"

foreach ($SPSite in $SPWebApp.Sites)
{
    if ($SPSite -ne $null)
    {
        foreach ($SPWeb in $SPSite.AllWebs)
        {
            Write-Host $SPWeb.Title

            if ($SPWeb -ne $null)
            {
                $SPWeb.Dispose()
            }
        }
    }

    if ($SPSite -ne $null)
    {
        $SPSite.Dispose()
    }
}

You also have the benefit of not missing a web inside an entire Web Application.