Saturday, July 14, 2012

How to loop through all SPWeb object in your SharePoint site using Powershell

If ever you need to loop through all your SPWeb object in a SharePoint site for whatever reason and you want to do it in powershell. Try out the below code snippet. It worked for me, hope it can help you.

Remove-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

$siteUrl = read-host "What is your site url? Eg: http://mysharepointpotal"
$site= Get-SPSite $siteURL
$webs= $site.AllWebs
    foreach ($web in $webs)
        Write-Host $web.url
        # Perform operation
    write-host -f Red "error" $_.exception
    $errorlabel = $true
And that's it, you can now loop through all SPWeb objects in your site.

Happy scripting :-)