How to list all the sub-sites and the site collections within a SharePoint web application using Windows Powershell

Recently, I worked on a partner's request for enumerating all the sub-sites and the site collection within a SharePoint web application. If you want to do the same thing, may this be useful for you.

Windows Powershell has made it so easy to work/administer with several Microsoft products like, SharePoint, SQL Server, Exchange Server etc., so that almost anyone who has some knowledge of Powershell programming can work with them.

Find out yourself by seeing the code below:

--------------------------------------------------

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$websvcs = $farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.SharePoint.Administration.SPWebService]}
$webapps = @()

foreach ($websvc in $websvcs) {
           write-host "Web Applications"
           write-host ""
    foreach ($webapp in $websvc.WebApplications) {
        write-host "Webapp Name -->"$webapp.Name
           write-host ""
           write-host "Site Collections"
           write-host ""
    foreach ($site in $webapp.Sites) {
        write-host "Site URL --> -->" $site.URL
           write-host ""
           write-host "Websites"
           write-host ""
    foreach ($web in $site.AllWebs) {
        write-host "Web URL --> --> -->" $web.URL
           write-host ""
           write-host "Lists"
           write-host ""
    foreach ($list in $web.Lists) {
           write-host "List Title --> --> --> -->" $list.Title
           write-host ""
    }

    foreach ($group in $web.Groups) {
           write-host "Group Name --> --> --> -->" $group.Name
           write-host ""

    foreach ($user in $group.Users) {
           write-host "User Name --> --> --> -->" $user.Name
           write-host ""
    }
    }

    }

    }

    }
}

--------------------------------------------------

Happy Programming!