Tuesday, June 2, 2015

Get all sites in a SharePoint Site Collection using the PowerShell and CSOM


$host.Runspace.ThreadOptions = "ReuseThread"

#Function definition
function Get-AllSites($siteUrl, $userName, $password, $domain)
{
    try
    {  
        #Save result in temp variable
        $results = @()

        #Create client context
        $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) 
        $credentials = New-Object System.Net.NetworkCredential($userName,$password,$domain)  
        $ctx.Credentials = $credentials 

        #Get site
        $rootSite = $ctx.Web
        
        #Loading root site     
        $ctx.Load($rootSite)
        $ctx.Load($rootSite.Webs)
        $ctx.ExecuteQuery()
       
        foreach($site in $rootSite.Webs){
           
            #Load sites under each subsite
            $ctx.Load($site)
            $ctx.Load($site.Webs)
            $ctx.ExecuteQuery()

            Write-Host $site.Url -ForegroundColor Green
           
            #Create object for CSV row           
            $details = new-object PSObject
            $details | add-member -membertype NoteProperty -name "Site URL" -Value $site.Url
            $results += $details

            #Go for subsites if it has child sites
            if($site.Webs.Count -gt 0) {

                $results += Get-AllSites $site.Url $userName $password $domain
            }
        
        }
        $ctx.Dispose()      
       
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()   
    }
   
    return $results
}

#Parameters
$siteUrl = "http://contoso/sites/hr"
$userName = "username"
$password ="password"
$domain="DOMAIN"


#Add Client Object Model Assemblies        
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Call fuction
$path = Get-Location
Get-AllSites $siteUrl $userName $password $domain | export-csv -Path $path\List.csv -NoTypeInformation

Write-Host "Report exported to CSV, please check file on location: $path"

Read-Host